Givenan array arr that is a permutation of [0, 1, ...,arr.length - 1], we split the array into some numberof "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.
Whatis the most number of chunks we could have made?
Example 1:
Input: arr = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return therequired result.
For example, splitting into [4, 3], [2, 1, 0] will result in[3, 4, 0, 1, 2], which isn't sorted.
Example 2:
Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highestnumber of chunks possible.
Note:
- arr will have length in range [1, 10].
- arr[i] will be a permutation of [0, 1, ..., arr.length - 1].
这题要求将数组划分成多个子数组,要求对每个子数组排序之后将这些子数组首位相接,刚好是0~n-1,n为原数组的大小
这题可以使用贪心算法解决
我们定义left和right,theMax,和theMin,theMax表示left和right之间所有的数里面最大的,theMin表示left和right之间所有的数里面最小的,当theMax等于left并且theMin等于right的时候,这个时候left和right之间的一个组就是包含数组最左边数的最小的一个组,因为原数组无论怎样划分,都有一个包含最左边数的最小的数组,所以以上的划分必然在最优划分里面
然后对right+1到n-1继续寻找包含nums[right+1]的符合要求的最小的数组,找到之后找到的这个数组必然包含在最终的符合要求的最佳的划分方案里面,
一直持续以上过程直到整个数组都划分完毕class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
int left, right, theMax, theMin,result=0;
left = right = 0;
theMax = theMin = arr[0];
while (right < arr.size())
{
if (arr[right] > theMax) theMax = arr[right];
if (arr[right] < theMin) theMin = arr[right];
if (theMin == left&&theMax == right)
{
result++;
if (right == arr.size() - 1) break;
left = right + 1;
right++;
theMax = theMin = arr[right];
continue;
}
right++;
}
return result;
}
};