Wood Cut
Written on October 21, 2015
Tweet
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.
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
if (L == null || L.length == 0) return 0;
Arrays.sort(L);
int lo = 1, hi = L[L.length - 1], len = 0; // lo starts from 1, not L[0]
while (lo <= hi) {
int count = 0;
int mid = lo + (hi - lo) / 2;//hi can be really large
for (int n : L) {
count += n / mid;
}
if (count >= k) {
lo = mid + 1;
len = mid;
} else {
hi = mid - 1;
}
}
return len;
}
}