Wood Cut(lintcode 183)

Description

Given n pieces of wood with length L[i] (integer array). Cut them into small pieces to guarantee you could have equal or more than k pieces with the same length. What is the longest length you can get from the n pieces of wood? Given L & k, return the maximum length of the small pieces.

Notice:
You couldn't cut wood into float length.

Example

For L=[232, 124, 456], k=7, return 114.

Interface

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
    }
}

Solution

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
        long sum = 0;
        for (int i = 0; i < L.length; ++i) {
            sum += L[i];
        }

        if (k < 1 || k > sum) {
            return 0;
        }

        Arrays.sort(L);
        int start = 1;
        int end = L[L.length - 1];

        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            int num = 0;

            for (int i = 0; i < L.length; ++i) {
                num += (L[i] / mid);
            }

            if (num < k) {
                end = mid;
            } else {
                start = mid;
            }
        }

        int lenStart = 0;
        int lenEnd = 0;
        for (int i = 0; i < L.length; ++i) {
            lenEnd += (L[i] / end);
            lenStart += (L[i] / start);
        }

        if (lenEnd >= k) {
            return end;
        } else if (lenStart >= k) {
            return start;
        }

        return 0;
    }
}

results matching ""

    No results matching ""