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 maximum number of chunks we can make to achieve this.
arr
cover the full range from [0, n-1]
without any missing or duplicate numbers?
arr
is a permutation of integers in the range [0, n-1]
.n
can be reasonably large but not excessively so (e.g., 1 <= n <= 10^5
).To solve this problem, the main idea is to iterate through the array and keep track of the maximum value seen so far. At any position i
, if the maximum value seen so far is equal to i
, it indicates that all the numbers from 0
to i
are present in some order up to that point. This means we can create a chunk ending at i
.
Here’s a step-by-step approach:
max_seen
).chunks
).max_seen
value to be the maximum of its current value and the current array value.max_seen
is equal to the current index i
, it means we can split and form a chunk. Increment the chunks
counter.This approach involves a single pass through the array, making it O(n)
in time complexity.
Here’s how you can implement this:
def maxChunksToSorted(arr):
max_seen = 0
chunks = 0
for i, value in enumerate(arr):
max_seen = max(max_seen, value)
if max_seen == i:
chunks += 1
return chunks
# Example Usage
arr = [1, 0, 2, 3, 4]
print(maxChunksToSorted(arr)) # Output: 4
arr = [1, 0, 2, 3, 4]
:
max_seen
is 1 (cannot form a chunk).max_seen
is still 1 and now it equals i
= 1, so we can form first chunk ([1, 0]
).max_seen
is 2 (cannot form a chunk).max_seen
is 3 and equals i
, so we can form another chunk ([2, 3]
).max_seen
is 4 and equals i
, so we can form another chunk ([4]
).Thus, the maximum number of chunks is 4.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?