MediumNo. 1891LeetCode Premium
Cutting Ribbons — LeetCode 1891 Python Solution
- Pattern
- Monotonic Stack
- Topics
- Array, Binary Search
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- ribbons = [9,7,5], k = 3
- Output
- 5
- Explanation
- - Cut the first ribbon to two ribbons, one of length 5 and one of length 4.
Python solution
class Solution:
def maxLength(self, ribbons: List[int], k: int) -> int:
left, right = 0, max(ribbons)
while left < right:
mid = (left + right + 1) >> 1
cnt = sum(x // mid for x in ribbons)
if cnt >= k:
left = mid
else:
right = mid - 1
return leftComplexity
- Time
- O(n × log M)where n and M are the number of ropes and the maximum length of the ropes, respectively
- Space · auxiliary
- O(1)
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 1891. Cutting Ribbons is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1889 | Minimum Space Wasted From Packaging | Hard |
| 1894 | Find the Student that Will Replace the Chalk | Medium |
| 1901 | Find a Peak Element II | Medium |
| 0004 | Median of Two Sorted Arrays | Hard |
| 0033 | Search in Rotated Sorted Array | Medium |
| 0034 | Find First and Last Position of Element in Sorted Array | Medium |
Frequently asked questions
- How hard is LeetCode 1891. Cutting Ribbons?
LeetCode 1891. Cutting Ribbons is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1891. Cutting Ribbons?
The Python solution on this page runs in O(n × log M), where n and M are the number of ropes and the maximum length of the ropes, respectively.
- What is the space complexity of LeetCode 1891. Cutting Ribbons?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1891. Cutting Ribbons cover?
LeetCode 1891. Cutting Ribbons is tagged Array and Binary Search on LeetCode.
- Is LeetCode 1891. Cutting Ribbons a premium problem?
Yes. LeetCode 1891. Cutting Ribbons is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.