768 Max Chunks To Make Sorted II

# 1. Question

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?
Example 1:
1
Input: arr = [5,4,3,2,1]
2
3
Output: 1
4
5
Explanation:
6
Splitting into two or more chunks will not return the required result.
7
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
Copied!
Example 2:
1
Input: arr = [2,1,3,4,4]
2
3
Output: 4
4
5
Explanation:
6
We can split into two chunks, such as [2, 1], [3, 4, 4].
7
However, splitting into [2, 1], , ,  is the highest number of chunks possible.
Copied!
Note:
• `arr`will have length in range`[1, 2000]`.
• `arr[i]`will be an integer in range`[0, 10**8]`.

# 2. Implementation

(1) DP

1
class Solution {
2
public int maxChunksToSorted(int[] arr) {
3
int n = arr.length;
4
5
int[] leftMax = new int[n];
6
int[] rightMin = new int[n];
7
8
int curMax = Integer.MIN_VALUE;
9
for (int i = 0; i < n; i++) {
10
curMax = Math.max(curMax, arr[i]);
11
leftMax[i] = curMax;
12
}
13
14
int curMin = Integer.MAX_VALUE;
15
for (int i = n - 1; i >= 0; i--) {
16
curMin = Math.min(curMin, arr[i]);
17
rightMin[i] = curMin;
18
}
19
20
int res = 0;
21
for (int i = 0; i < n - 1; i++) {
22
if (leftMax[i] <= rightMin[i + 1]) {
23
++res;
24
}
25
}
26
return res + 1;
27
}
28
}
Copied!

# 3. Time & Space Complexity

DP: 时间复杂度O(n), 空间复杂度O(n)