LintCode 183. Wood Cut
183.Wood Cut
Example
Challenge
Notice
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?