Wood Cut

Description

Given n pieces of wood with lengthL[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.

If you couldn't get >=_k_pieces, return0.

Example

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

Challenge

O(n log Len), where Len is the longest length of the wood.

Implementation

Link: http://lintcode.com/en/problem/wood-cut/

class Solution {
public:
    /** 
     *@param L: Given n pieces of wood with length L[i]
     *@param k: An integer
     *return: The maximum length of the small pieces.
     */
    int woodCut(vector<int> L, int k) {
        // write your code here
        int maxLen = 0;

        for(int i = 0; i < L.size(); i++)
            maxLen = max(maxLen, L[i]);

        int start = 1;
        int end = maxLen;

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

            if(cut(L, mid) >= k){
                start = mid;
            }else{
                end = mid;
            }
        }

        if(cut(L, end) >= k) return end;
        if(cut(L, start) >= k) return start;
        return 0;
    }

    int cut(vector<int> & L, int size){
        int sum = 0;
        for(int i = 0; i < L.size(); i++)
            sum += L[i]/size;
        return sum;
    }
};

results matching ""

    No results matching ""