Cutting Ribbons — LeetCode 1891 Python Solution
- Problem
- #1891
- Pattern
- Monotonic Stack
- 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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M), where n and M are the number of ropes and the maximum length of the ropes, respectively |
| Space | O(1) auxiliary |
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
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 \times \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.