Binary Search
The paradigm:
- Having
leftandrightindices - Evaluate
mid - Based on the evaluation, update
leftorrightaccordingly - When
left < rightcondition is not met, return
Segmenting ribbons
- An array
a, each elementa[i]represents the length of a ribbon. - Obtain
kribbons of the same length, by cutting the ribbons. - Calculate maximum integer length
Lthat is possible to obtainkribbons.
lo, hi = 1, sum(a) // k
while lo <= hi:
mid = (lo + hi) // 2
possible = sum([r // mid for r in a])
# Updating lo and hi
return lo - 1There are two ways to update lo and hi.
# First
if possible: lo += 1
else: hi -= 1
# More efficient
if possible: lo = mid + 1
else : hi = mid - 1