您的位置:首页 > 其它

Wood Cut

2016-12-13 10:44 95 查看
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.


 Notice


You couldn't cut wood into float length.

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) {
if(L == null || L.length == 0 || k == 0) {
return 0;
}
int len = L[0];
for(int l: L) {
len = Math.max(len, l);
}
int start = 0;
int end = len;
while(start + 1 < end) {
int mid = start + (end - start) / 2;
int count = cut(L, mid);
if(count < k) {
end = mid;
} else {
start = mid;
}
}
if(cut(L, end) >= k) {
return end;
} else {
return start;
}
}

private int cut(int[] L, int len) {
int count = 0;
for(int l: L) {
count += l / len;
}
return count;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  binary search