Wood Cut
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.
Example For L=[232, 124, 456], k=7, return 114.
Notes:
- Binary Search on Result
- The piece must be between 1 and the largest piece
- Choose the middle piece, calculate the number with this piece size to cut the woods (Binary Search)
- Change start/end according to the comparison between number and k.
- Find the maximum length, so don't stop when meet k, continue to find bigger one
Time: O(nLogLength)
public int woodCut(int[] L, int k) {
if (L == null || L.length == 0) {
return 0;
}
// find the largest one
int end = findLargest(L);
int start = 1;
while(start + 1 < end) {
int middle = start + (end-start)/2;
int num = cut(L, middle);
if (num >= k) {
start = middle;
} else {
end = middle;
}
}
if (cut(L, end) >= k) {
return end;
}
if (cut(L, start) >= k) {
return start;
}
return 0;
}
private int findLargest(int[] L) {
int largest = L[0];
for (int i = 1; i < L.length; ++i) {
largest = Math.max(largest, L[i]);
}
return largest;
}
private int cut(int[] L, int l) {
int num = 0;
for (int i = 0; i < L.length; ++i) {
num += L[i]/l;
}
return num;
}