Max Chunks To Make Sorted

You are given an integer array `arr` of length `n` that is a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (partitions) and sort each chunk individually. After concatenating the sorted chunks, the result must equal the sorted array. Return *the largest number of chunks we can make to sort the array*.

30:00

Max Chunks To Make Sorted
medium
Free written solution
Topics
Companies

You are given an integer array arr of length n that is a permutation of the integers in the range [0, n - 1].

We split arr into some number of chunks (partitions) and sort each chunk individually. After concatenating the sorted chunks, the result must 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
Constraints:
  • n==arr.lengthn == \text{arr.length}

  • 1≤n≤101 \leq n \leq 10

  • 0≤arr[i]<n0 \leq \text{arr}[i] < n

  • All the elements of arr are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[4,3,2,1,0]}

Each chunk is stored on the stack by its largest value. A new value may start its own chunk only if it is bigger than every value before it; otherwise it must join the chunks whose maxima exceed it.

arr split into chunks

4
3
2
1
0

stack of chunk maxima

empty

chunks

0

Variables
VariableValue
stack[]
DepthFunction Call
Stack empty
0/15