Problem
Given an integer array woods, where each value represents the length of a piece of wood, and an integer k, find the maximum integer length such that the wood can be cut into at leastk pieces of that length.
Each piece of wood can be cut independently, and leftover wood can be discarded. Return the maximum possible length.
Example(s)
Example 1
Input
woods = [5,9,7]
k = 3
Output
5
Example 2
Input
woods = [5,9,7]
k = 5
Output
3
Solution
This problem can be solved using Binary Search on the Answer. Instead of searching for a value in an array, we search for the maximum possible wood length.For a candidate length
mid, we calculate how many pieces can be obtained from each wood using wood / mid. If the total number of pieces is at least k, the candidate length is possible, so we try a larger length. Otherwise, we try a smaller length.
The key observation is that if a length is possible, every smaller length is also possible. Similarly, if a length is not possible, every larger length is also impossible. This monotonic property allows us to use Binary Search.
class Solution {
public int cutWood(int[] woods, int k) {
int left = 1;
int right = 0;
for (int wood : woods) {
right = Math.max(right, wood);
}
int result = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
long pieces = 0;
for (int wood : woods) {
pieces += wood / mid;
}
if (pieces >= k) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
}
Complexity
Letn be the number of wood pieces and M be the maximum wood length. Binary Search performs O(log M) iterations, and each iteration checks all n pieces. Therefore, the time complexity is O(n log M).
The algorithm uses only a few variables, so the extra space complexity is
O(1).
Comments
No comments yet. Ask a question or share what helped.