题目:
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:
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.
Note:
arr
will have length in range[1, 2000]
.arr[i]
will be an integer in range[0, 10**8]
.
思路:
通过观察可知,如果在某个位置,左边最大的数比右边最小的数都大,那么说明就需要新分割出来一个chunk了。为了在线性时间复杂度内解决问题,我们额外定义一个数组right_min,其中right_min[i]表示在i的右边(包含i本身)的最小数。然后从左到右扫描数组,并记录截止当前的最大数。如果一旦发现其左边的最大数要大于等于右边的最小数,就新开始一个chunk(当然此时还需要更新left_max的值)。
算法的时间复杂度是O(n),空间复杂度也是O(n)。
代码:
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
int n = arr.size();
vector<int> right_min(n, 0); // right_min[i] means the min value to its right
right_min[n - 1] = arr[n - 1];
for( int i = n - 2; i >= 0; --i) {
right_min[i] = min(arr[i], right_min[i+1]);
}
int ans = 1, left_max = arr[0];
for (int i = 1; i < n; ++i) {
if (right_min[i] < left_max) { // the right side has small value(s), hence cannot split
left_max = max(left_max, arr[i]);
}
else {
++ans;
left_max = arr[i];
}
}
return ans;
}
};