Max Chunks To Make Sorted — LeetCode 769 Python Solution
MediumStackGreedyArraySortingMonotonic Stack
- Problem
- #769
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1]. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk.
Example
- Input
- arr = [4,3,2,1,0]
- 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:
mx = ans = 0
for i, v in enumerate(arr):
mx = max(mx, v)
if i == mx:
ans += 1
return ansComplexity
| 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 769. Max Chunks To Make Sorted 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 769. Max Chunks To Make Sorted?
- LeetCode 769. Max Chunks To Make Sorted is rated Medium on LeetCode.
- What topics does LeetCode 769. Max Chunks To Make Sorted cover?
- LeetCode 769. Max Chunks To Make Sorted is tagged Stack, Greedy, Array, Sorting and Monotonic Stack on LeetCode.