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.
Input: arr =[5,4,3,2,1]Output: 1Explanation:
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:
1
2
3
4
5
Input: arr =[2,1,3,4,4]Output: 4Explanation:
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.
Maintain Maximum Value Up to Current Index: Track the maximum value encountered up to each index while iterating through the array.
Identify Chunks: When the maximum value equals the current index, it means all previous elements can form a valid chunk because they include all necessary integers up to that point.
Track Chunks: Each time the above condition is met, increment the count of chunks.
publicclassSolution {
publicintmaxChunksToSorted(int[] arr) {
int n = arr.length;
int[] max =newint[n];
int count = 0;
max[0]= arr[0];
for (int i = 1; i < n; i++) {
max[i]= Math.max(max[i - 1], arr[i]);
}
for (int i = 0; i < n; i++) {
if (max[i]== i) {
count++;
}
}
return count;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defmaxChunksToSorted(self, arr: List[int]) -> int:
n: int = len(arr)
max_arr: List[int] = [0] * n
max_arr[0] = arr[0]
count: int =0for i in range(1, n):
max_arr[i] = max(max_arr[i -1], arr[i])
for i in range(n):
if max_arr[i] == i:
count +=1return count