Max Chunks To Make Sorted II — LeetCode 768 Python Solution
HardStackGreedyArraySortingMonotonic Stack
- Problem
- #768
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array arr. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk.
Example
- Input
- arr = [5,4,3,2,1]
- Output
- 1
- Explanation
- Splitting into two or more chunks will not return the required result.
Python solution
Python
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
stk = []
for v in arr:
if not stk or v >= stk[-1]:
stk.append(v)
else:
mx = stk.pop()
while stk and stk[-1] > v:
stk.pop()
stk.append(mx)
return len(stk)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 768. Max Chunks To Make Sorted II is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 768. Max Chunks To Make Sorted II?
- LeetCode 768. Max Chunks To Make Sorted II is rated Hard on LeetCode.
- What topics does LeetCode 768. Max Chunks To Make Sorted II cover?
- LeetCode 768. Max Chunks To Make Sorted II is tagged Stack, Greedy, Array, Sorting and Monotonic Stack on LeetCode.