Wood Cut(木材加工)

http://www.lintcode.com/zh-cn/problem/wood-cut/

public class Solution {
    /*
     * @param L: Given n pieces of wood with length L[i]
     * @param k: An integer
     * @return: The maximum length of the small pieces
     */
    public int woodCut(int[] L, int k) {
        // write your code here
//        用二分法,左边是1,右边是L中的最大值,mid表示最后要求的值。
        int r = 0;
        for (int i = 0; i < L.length; i++) {
            r = Math.max(L[i], r);
        }
        int l = 1;
        int res = Integer.MIN_VALUE;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            int count = getCount(mid, L);
            if (count < k) {
//                小于k时,说明数量不够,只能让最后得到的值更小才能得到理多的数目
                r = mid - 1;
            } else {
//                当大于k时,说明符合条件了。记录下结果
                res = Math.max(res, mid);
//                尽量让最后的值更大
                l = mid + 1;
            }
        }
        return res == Integer.MIN_VALUE ? 0 : res;
    }

    private int getCount(int mid, int[] l) {
        int count = 0;
        for (int i = 0; i < l.length; i++) {
            count += l[i] / mid;
        }
        return count;
    }
}

你可能感兴趣的:(Wood Cut(木材加工))