#768
Hard Algorithms Max chunks to make sorted ii
Array Stack Greedy Sorting Monotonic Stack
54.7% acceptance
Feb 21, 2026
1995
63
You are given an integer array arr.
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Solution
Rust
Time O(n)
Space O(n)
/*
* You are given an integer array arr.
* We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
* Return the largest number of chunks we can make to sort the array.
* Example 1:
* Input: arr = [5,4,3,2,1]
* Output: 1
* Explanation:
* Splitting into two or more chunks will not return the required result.
* For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
* Example 2:
* Input: arr = [2,1,3,4,4]
* Output: 4
* Explanation:
* We can split into two chunks, such as [2, 1], [3, 4, 4].
* However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
* Constraints:
* 1 <= arr.length <= 2000
* 0 <= arr[i] <= 108
*/
impl Solution {
pub fn max_chunks_to_sorted(arr: Vec<i32>) -> i32 {
let n = arr.len();
let mut min_right = vec![i32::MAX; n + 1];
for i in (0..n).rev() {
min_right[i] = min_right[i + 1].min(arr[i]);
}
let mut chunks = 0;
let mut max_left = i32::MIN;
for i in 0..n {
max_left = max_left.max(arr[i]);
if max_left <= min_right[i + 1] {
chunks += 1;
}
}
chunks
}
}