Cutting Ribbons - Problem
Imagine you're a craft store owner with various ribbons of different lengths, and a customer needs k ribbons of identical length for a special project. Your job is to find the maximum possible length you can cut to satisfy their request!
Given an array ribbons where ribbons[i] represents the length of the i-th ribbon, and an integer k, you need to determine the maximum length x such that you can cut at least k ribbons each of length x.
Key Rules:
- You can cut any ribbon into smaller pieces of positive integer lengths
- You can discard leftover pieces from cuts
- If it's impossible to get
kribbons of the same length, return0
Example: With a ribbon of length 4, you could cut it into: one piece of length 4, or one of length 3 + one of length 1, or two pieces of length 2, etc.
Input & Output
example_1.py โ Basic Case
$
Input:
ribbons = [9,7,5], k = 3
โบ
Output:
5
๐ก Note:
We can cut the ribbons into: ribbon 9 โ one piece of length 5 (discard 4), ribbon 7 โ one piece of length 5 (discard 2), ribbon 5 โ one piece of length 5. Total: 3 pieces of length 5.
example_2.py โ Multiple Cuts Per Ribbon
$
Input:
ribbons = [7,5,9], k = 4
โบ
Output:
4
๐ก Note:
We can cut: ribbon 7 โ one piece of length 4, ribbon 5 โ one piece of length 4, ribbon 9 โ two pieces of length 4. Total: 4 pieces of length 4.
example_3.py โ Impossible Case
$
Input:
ribbons = [5,7,9], k = 22
โบ
Output:
0
๐ก Note:
Even if we cut all ribbons into pieces of length 1, we get 5+7+9 = 21 pieces, which is less than 22. Therefore, it's impossible.
Constraints
- 1 โค ribbons.length โค 105
- 1 โค ribbons[i] โค 105
- 1 โค k โค 109
- All ribbon lengths are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Identify the search space
The answer must be between 1 and the longest ribbon
2
Use binary search property
If length X works, all smaller lengths also work
3
Count efficiently
For each candidate length, count total pieces possible
4
Converge to optimum
Binary search finds the maximum valid length
Key Takeaway
๐ฏ Key Insight: Binary search works because of the monotonic property - if we can create k ribbons of length X, we can definitely create k ribbons of any length smaller than X!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code