# 768. Max Chunks To Make Sorted II

## Description

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

## Solutions

• class Solution {
public int maxChunksToSorted(int[] arr) {
Deque<Integer> stk = new ArrayDeque<>();
for (int v : arr) {
if (stk.isEmpty() || stk.peek() <= v) {
stk.push(v);
} else {
int mx = stk.pop();
while (!stk.isEmpty() && stk.peek() > v) {
stk.pop();
}
stk.push(mx);
}
}
return stk.size();
}
}

• class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
stack<int> stk;
for (int& v : arr) {
if (stk.empty() || stk.top() <= v)
stk.push(v);
else {
int mx = stk.top();
stk.pop();
while (!stk.empty() && stk.top() > v) stk.pop();
stk.push(mx);
}
}
return stk.size();
}
};

• 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)


• func maxChunksToSorted(arr []int) int {
var stk []int
for _, v := range arr {
if len(stk) == 0 || stk[len(stk)-1] <= v {
stk = append(stk, v)
} else {
mx := stk[len(stk)-1]
stk = stk[:len(stk)-1]
for len(stk) > 0 && stk[len(stk)-1] > v {
stk = stk[:len(stk)-1]
}
stk = append(stk, mx)
}
}
return len(stk)
}

• function maxChunksToSorted(arr: number[]): number {
const stack = [];
for (const num of arr) {
if (stack.length !== 0 && num < stack[stack.length - 1]) {
const max = stack.pop();
while (stack.length !== 0 && num < stack[stack.length - 1]) {
stack.pop();
}
stack.push(max);
} else {
stack.push(num);
}
}
return stack.length;
}


• impl Solution {
pub fn max_chunks_to_sorted(arr: Vec<i32>) -> i32 {
let mut stack = vec![];
for num in arr.iter() {
if !stack.is_empty() && num < stack.last().unwrap() {
let max = stack.pop().unwrap();
while !stack.is_empty() && num < stack.last().unwrap() {
stack.pop();
}
stack.push(max);
} else {
stack.push(*num);
}
}
stack.len() as i32
}
}