This question is the same as “Max Chunks to Make Sorted” except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8.


Given an array arr of integers (not necessarily distinct), we split the array into some number of “chunks” (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

1
2
3
4
5
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.
1
2
3
4
5
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.

Almost impossible

Two arrays. Compare continuous sum.

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int maxChunksToSorted(int[] arr) {
int n = arr.length, res = 0;
double sum1 = 0, sum2 = 0;
int[] tmp = new int[n];
System.arraycopy(arr, 0, tmp, 0, arr.length);
Arrays.sort(tmp);
for (int i = 0; i < n; ++i) {
sum1 += arr[i];
sum2 += tmp[i];
if (sum1 == sum2) {
++res;
}
}
return res;
}

C++:

1
2
3
4
5
6
7
8
9
10
11
12
int maxChunksToSorted(vector<int>& arr) {
double sum1 = 0, sum2 = 0;
int ans = 0;
vector<int> t = arr;
sort(t.begin(), t.end());
for(int i = 0; i < arr.size(); i++) {
sum1 += t[i];
sum2 += arr[i];
if(sum1 == sum2) ans++;
}
return ans;
}

leftMax, rightMin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

public int maxChunksToSorted(int[] arr) {
int n = arr.length;
int[] leftMax = new int[n];
int[] rightMin= new int[n];

leftMax[0] = arr[0];
for (int i = 1; i < n-1; i++) {
leftMax[i] = Math.max(leftMax[i-1], arr[i]);
}

rightMin[n-1] = arr[n-1];
for (int i = n-2; i >= 0; --i) {
rightMin[i] = Math.min(rightMin[i+1], arr[i]);
}

int res = 1;
for (int i = 0; i < n-1; ++i) {
if (leftMax[i] <= rightMin[i+1]) ++res;
}
return res;
}