1891.Cutting Ribbons
Problem description:
You are given an integer array ribbons
, where ribbons[i]
represents the length of the ith
ribbon, and an integer k
. You may cut any of the ribbons into any number of segments of positive integer lengths, or perform no cuts at all.
- For example, if you have a ribbon of length
4
, you can:- Keep the ribbon of length
4
, - Cut it into one ribbon of length
3
and one ribbon of length1
, - Cut it into two ribbons of length
2
, - Cut it into one ribbon of length
2
and two ribbons of length1
, or - Cut it into four ribbons of length
1
.
- Keep the ribbon of length
Your goal is to obtain k
ribbons of all the same positive integer length. You are allowed to throw away any excess ribbon as a result of cutting.
Return the maximum possible positive integer length that you can obtain k
ribbons of, or 0
if you cannot obtain k
ribbons of the same length.
Example 1:
1 | Input: ribbons = [9,7,5], k = 3 |
Example 2:
1 | Input: ribbons = [7,5,9], k = 4 |
Example 3:
1 | Input: ribbons = [5,7,9], k = 22 |
Constraints:
1 <= ribbons.length <= 105
1 <= ribbons[i] <= 105
1 <= k <= 109
Solution:
Binary search on length we want to cut.
If a length mid
could make greater or equal to k ribbons, then we found a left boundary
notice we use (l+r+1)//2
to find mid, because we want to advance mid after left boundary
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: