#769

Max Chunks To Make Sorted

Medium
ArrayStackGreedySortingMonotonic StackGreedyTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the property of permutations. By keeping track of the maximum value encountered so far, we can determine how many chunks we can form without needing to sort.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to keep track of the maximum value seen as we iterate through the array.
  2. 2Step 2: For each element in the array, update the maximum value.
  3. 3Step 3: If the current index matches the maximum value, it indicates a valid chunk, increment the chunk count.
solution.py9 lines
1def maxChunksToSorted(arr):
2    max_chunks = 0
3    max_value = 0
4    for i in range(len(arr)):
5        max_value = max(max_value, arr[i])
6        if max_value == i:
7            max_chunks += 1
8    return max_chunks
9

Complexity note: This complexity is linear because we only make a single pass through the array, updating the maximum value and counting chunks.

  • 1The maximum value encountered at each index helps determine valid chunks.
  • 2The problem can be solved in linear time by leveraging properties of permutations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.