Imagine you have an array of integers that needs to be sorted, but instead of sorting it directly, you want to split it into chunks first. Each chunk can be sorted independently, and when you concatenate all the sorted chunks together, the result should be identical to sorting the entire array at once.
Your goal: Find the maximum number of chunks you can create while still achieving a perfectly sorted final array.
Key insight: Unlike the simpler version of this problem, this array can contain duplicate values and the values are not restricted to be a permutation of indices.
Example: For array [2,1,3,4,4], you could split it as [2,1] | [3] | [4,4]. After sorting each chunk: [1,2] + [3] + [4,4] = [1,2,3,4,4], which matches the fully sorted array. This gives us 3 chunks, which is the maximum possible.
Input & Output
Visualization
Time & Space Complexity
2^(n-1) partitions to try, each requiring O(n log n) sorting and O(n) comparison
Space for storing chunks and sorted arrays
Constraints
- 1 โค arr.length โค 2000
- 0 โค arr[i] โค 108
- Array elements can be duplicated (unlike the simpler version)
- Array elements are not restricted to be permutations of indices