Max Chunks To Make Sorted LeetCode
You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].
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 = [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.
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 highest number of chunks possible.
Approach 1 :
Using Left Max and Right Min Arrays
Idea:
Instead of tracking only the maximum, we can also maintain the right minimum values.
-
leftMax[i]
: Stores the maximum value from index0
toi
. -
rightMin[i]
: Stores the minimum value from indexi
ton-1
. -
A valid chunk is where
leftMax[i] <= rightMin[i+1]
, meaning all elements in the left partition are smaller than the right partition.
Steps:
-
Compute
leftMax[]
such thatleftMax[i]
stores the maximum element from0
toi
. -
Compute
rightMin[]
such thatrightMin[i]
stores the minimum element fromi
ton-1
. -
Count the chunks where
leftMax[i] <= rightMin[i+1]
.
Approach 2:-
Intuition:
We don't need extra arrays (leftmax
and rightmin
) to find the maximum chunks. Instead, we can track the maximum value seen so far while iterating through the array.
Key Observations:
-
If, at any index
i
, the maximum element so far (maxSoFar
) is equal toi
, then all elements from index0
toi
form a valid chunk. -
This is because, in a sorted version of the array, elements
0
toi
must be in the range[0, i]
, ensuring that they are already in their correct relative order.
Algorithm:
-
Initialize
maxSoFar = 0
andchunks = 0
. -
Iterate through the array:
-
Update
maxSoFar = max(maxSoFar, arr[i])
to track the maximum element seen so far. -
If
maxSoFar == i
, it means elements from0
toi
form a valid chunk, so increasechunks
.
-
-
Return
chunks
at the end.
Comments
Post a Comment