Max Chunks To Make Sorted II - Problem

You are given an integer array arr. 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 largest number of chunks we can make to sort the array.

Input & Output

Example 1 — Basic Case
$ Input: arr = [5,4,3,2,1]
Output: 1
💡 Note: The array is already in reverse order. No matter how we split it, we need all elements together to form the sorted sequence [1,2,3,4,5]. Only 1 chunk is possible.
Example 2 — Multiple Chunks Possible
$ Input: arr = [2,1,3,4,4]
Output: 4
💡 Note: We can split as [2,1] | [3] | [4] | [4]. After sorting each chunk: [1,2] + [3] + [4] + [4] = [1,2,3,4,4], which matches the sorted array.
Example 3 — Already Sorted
$ Input: arr = [1,2,3,4,5]
Output: 5
💡 Note: Array is already sorted, so we can make each element its own chunk: [1] | [2] | [3] | [4] | [5]. Maximum possible chunks.

Constraints

  • 1 ≤ arr.length ≤ 2000
  • 0 ≤ arr[i] ≤ 108

Visualization

Tap to expand
Max Chunks To Make Sorted II INPUT Array: arr 5 [0] 4 [1] 3 [2] 2 [3] 1 [4] Sorted version: 1 2 3 4 5 Goal: Find max chunks that when sorted and concatenated = sorted array Constraints: 1 <= arr.length <= 2000 0 <= arr[i] <= 10^8 ALGORITHM STEPS 1 Build Prefix Max Track max from left to i prefixMax: [5,5,5,5,5] 2 Build Suffix Min Track min from i to right suffixMin: [1,1,1,1,1] 3 Find Chunk Boundaries Where prefixMax[i] <= suffixMin[i+1] 4 Count Valid Chunks Count positions where condition holds + 1 Analysis for [5,4,3,2,1]: i=0: max=5 vs min[1]=1 5>1 NO i=1: max=5 vs min[2]=1 5>1 NO i=2: max=5 vs min[3]=1 5>1 NO i=3: max=5 vs min[4]=1 5>1 NO FINAL RESULT Only 1 chunk possible: CHUNK 1 5 4 3 2 1 Sort chunk --> 1 2 3 4 5 OUTPUT 1 Verification: OK Sorted chunk = Sorted array Key Insight: A valid chunk boundary exists at position i if all elements to the left are smaller than or equal to all elements to the right. This is checked by comparing prefix max with suffix min. For descending array [5,4,3,2,1], no valid split exists since max element 5 is at the start. TutorialsPoint - Max Chunks To Make Sorted II | Greedy Approach with Prefix Analysis
Asked in
Google 42 Amazon 28 Facebook 15 Microsoft 12
89.3K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen