# Program to find maximum length of k ribbons of same length in Python

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 −

• left := 0
• right := maximum of ribbons
• while left < right, do
• mid := floor of (left + right + 1) / 2
• if sum of all elements present in the list containing (floor of ribbonLen / mid for each ribbonLen in ribbons which are at least k), then
• left := mid
• otherwise,
• right := mid - 1
• if left is non-zero, then
• return left
• return -1

## Example

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))

## Input

[1, 2, 5, 7, 15], 5

## Output

5