Wood Cut
ID; 183; hard; 木材加工
Solution 1 (Java)
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)
return 0;
int maxLength = findMaxWoodLength(L);
int left = 1, right = maxLength;
while (left + 1 < right) {
int mid = left + (right - left) / 2;
int counts = countPieces(L, mid);
if (counts >= k) {
left = mid;
} else {
right = mid;
}
}
if (countPieces(L, right) >= k) return right;
if (countPieces(L, left) >= k) return left;
return 0;
}
private int findMaxWoodLength(int[] L) {
int max = 0;
for (int l : L) {
max = Math.max(max, l);
}
return max;
}
private int countPieces(int[] L, int cutLength) {
int counts = 0;
for (int l : L) {
counts += l / cutLength;
}
return counts;
}
}Notes
Last updated