#768
Max Chunks To Make Sorted II
HardArrayStackGreedySortingMonotonic StackGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach uses a greedy strategy to determine where to split the array by comparing the maximum value seen so far with the sorted version of the array. This allows us to find valid chunks efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Create a sorted version of the array.
- 2Step 2: Initialize variables for the current maximum and chunk count.
- 3Step 3: Iterate through the array, updating the current maximum and comparing it with the sorted version at each index.
- 4Step 4: If the current maximum equals the index, increment the chunk count.
solution.py9 lines
1def maxChunksToSorted(arr):
2 sorted_arr = sorted(arr)
3 max_chunks = 0
4 current_max = 0
5 for i in range(len(arr)):
6 current_max = max(current_max, arr[i])
7 if current_max == sorted_arr[i]:
8 max_chunks += 1
9 return max_chunksℹ
Complexity note: The time complexity is O(n log n) due to sorting the array, while the space complexity is O(n) for storing the sorted array.
- 1Understanding how to compare the maximum values helps in determining valid chunks.
- 2Sorting the array is crucial to find the correct positions for the chunks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.