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] <= 10^8
【C++】
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
vector<int> mx = arr, mi = arr;
for (int i = 1 ; i < arr.size(); i++) {mx[i] = max(arr[i] , mx[i-1]);}
for (int i = arr.size() - 2; i >= 0; i--) {mi[i] = min(arr[i] , mi[i+1]);}
int res = 1;
for (int i = 0; i < arr.size() - 1; i++) {if(mx[i] <= mi[i+1]) {res++;}}
return res;
}
};
【Java】
class Solution {
public int maxChunksToSorted(int[] arr) {
int[] mx = arr.clone(), mi = arr.clone();
for (int i = 1 ; i < arr.length; i++) {mx[i] = Math.max(arr[i] , mx[i-1]);}
for (int i = arr.length - 2; i >= 0; i--) {mi[i] = Math.min(arr[i] , mi[i+1]);}
int res = 1;
for (int i = 0; i < arr.length - 1; i++) {if(mx[i] <= mi[i+1]) {res++;}}
return res;
}
}
参考文献