Suppose we have a list of positive numbers, representing ribbons length and also have one value k. We can cut the ribbons as many times as we want, we have to find the largest length r such that we can have k ribbons of length r. If we cannot find such solution, return -1.
So, if the input is like ribbons = [1, 2, 5, 7, 15] k = 5, then the output will be 5, as we can cut the ribbon of size 15 into 3 pieces of length 5 each. Then cut the ribbon of size 7 into size 2 and 5. And there is another ribbon of size 5, so we are getting 5 ribbons in total of size 5.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(ribbons, k): left = 0 right = max(ribbons) while left < right: mid = (left + right + 1) // 2 if sum((ribbonLen // mid for ribbonLen in ribbons)) >= k: left = mid else: right = mid - 1 if left: return left return -1 ribbons = [1, 2, 5, 7, 15] k = 5 print(solve(ribbons, k))
[1, 2, 5, 7, 15], 5