769. Max Chunks To Make Sorted
769. Max Chunks To Make Sorted
[Problem]
Array Stack Greedy Sorting Monotonic Stack
Intuition
- The key observation is that a chunk can end at index
iif the maximum value encountered so far (maxSoFar) is equal toi. - This ensures all values in the chunk are valid for their positions in the sorted array.
Approach
maxSoFar: Tracks the maximum value seen so far in the array.cnt: Counter to store the number of valid chunks.- For each index
i:- Update
maxSoFaras the maximum ofmaxSoFarandarr[i]. - Check if
maxSoFarequalsi. If true, increment the chunk counter (cnt).
- Update
- Return
cnt
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Reference Image
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int maxChunksToSorted(int[] arr) {
int n = arr.length;
int maxSoFar = 0;
int cnt = 0;
for(int i = 0; i < n; i++){
maxSoFar = Math.max(maxSoFar, arr[i]);
if(maxSoFar == i){
cnt += 1;
}
}
return cnt;
}
}
This post is licensed under CC BY 4.0 by the author.
