Max Chunks To Make Sorted II leetCode
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.
class Solution {
public int maxChunksToSorted(int[] arr) {
int n = arr.length;
int[] leftmax = new int[n]; // Array to store the maximum values from left to current index
int[] rightmin = new int[n]; // Array to store the minimum values from current index to right
// Initialize leftmax array
leftmax[0] = arr[0];
for (int i = 1; i < n; i++) {
// leftmax[i] stores the maximum value from index 0 to i
leftmax[i] = Math.max(leftmax[i - 1], arr[i]);
}
// Initialize rightmin array
rightmin[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--) {
// rightmin[i] stores the minimum value from index i to n-1
rightmin[i] = Math.min(rightmin[i + 1], arr[i]);
}
int chunk = 0; // Count the number of valid chunks
// Iterate through the array to find valid chunking points
for (int i = 0; i < n - 1; i++) {
// If the max in the left partition is smaller than the min in the right partition,
// it means we can form a valid chunk
if (leftmax[i] <= rightmin[i + 1]) {
chunk++;
}
}
// The final chunk count is incremented by 1 because the last segment is always a chunk
return chunk + 1;
}
}
Comments
Post a Comment