Given an array arr that is a permutation of [0, 1, …, arr.length - 1], 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 = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn’t sorted.
给出一个数组[0,1, …, arr.length-1], 把这个数组分成块,每块单独排序,接起来之后要是一个升序的数组,问最多能分多少块。
思路:
因为是每块单独排序,所以较大的数字出现在前面时不能单独分块,比如[2,1],2出现在1前面,2不能单独分块,不然1就不能参与前面2这块的排序,2和1这两块排好序接起来以后是[2,1],不是升序的[1,2]
遍历数组,到一个数字时,要保证它前面比它小的数字都要出现过,才能在此处分成一块。
定义一个变量,表示到目前为止的最大值,如果最大值==当前index,就表示比当前数字小的都出现过(因为数字是0~arr.length-1),分块数++。
分块数初始化为0,从index=0开始遍历,而不是1,初始化为1的话中间必然会出现满足最大值==当前index的条件,会再次+1,如arr = [4,3,2,1,0]
public int maxChunksToSorted(int[] arr) {
int n = arr.length;
int maxNum = 0;
int result = 0;
for(int i = 0; i < n; i++) {
maxNum = Math.max(maxNum, arr[i]);
if(maxNum == i) {
result ++;
}
}
return result;
}