Cutting Ribbons — Binary Search on Answer (Length)
Advertisement
Problem 344 · Cutting Ribbons
Difficulty: Hard · Pattern: BS on Answer (maximize)
Find the maximum length m such that you can cut at least k ribbons of length m.
Solutions
# Python
def maxLength(ribbons, k):
def feasible(length):
return sum(r // length for r in ribbons) >= k
lo, hi = 1, max(ribbons)
while lo < hi:
mid = lo + (hi-lo+1)//2 # upper mid (maximize)
if feasible(mid): lo = mid
else: hi = mid-1
return lo if feasible(lo) else 0
// Java
public int maxLength(int[] ribbons, int k) {
int lo=1, hi=0;
for (int r:ribbons) hi=Math.max(hi,r);
while (lo<hi) {
int mid=lo+(hi-lo+1)/2, cnt=0;
for (int r:ribbons) cnt+=r/mid;
if (cnt>=k) lo=mid; else hi=mid-1;
}
long cnt=0; for (int r:ribbons) cnt+=r/lo;
return cnt>=k?lo:0;
}
Complexity
- Time: O(n log max)
- Space: O(1)
Advertisement