LintCode 183. Wood Cut
183.Wood Cut
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.
Example
ForL=[232, 124, 456],k=7, return114.
Challenge
O(n log Len), where Len is the longest length of the wood.
Notice
You couldn't cut wood into float length.
If you couldn't get >=_k _pieces, return0.
Thoughts:
Binary Search on the length by testing the resulted cutting pieces
Code: T: Nlog(max(L[i])), S: O(1)
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
int l = 1, r = 0;
for (int len : L){
r = Math.max(r, len);
}
if(k == 0) return r;
while (l <= r){
int mid = l + ((r - l) >> 1);
if (count(L, mid) >= k) l = mid + 1;
else r = mid - 1;
}
// if (count(L,l) >= k) return l;
if (count(L,r) >= k) return r;
return 0;
}
private int count(int[] L, int query){
int sum = 0;
if (query == 0) return 0; // in case of dividing with 0
for (int len : L){
sum+= len/query;
}
return sum;
}
}Last updated
Was this helpful?