Talentd
FleetCode

768. Max Chunks To Make Sorted II

Hard54.7% acceptance5 companies

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.

Example 1:

Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.

Example 2:

Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.

Constraints:

  • 1 <= arr.length <= 2000
  • 0 <= arr[i] <= 108

Hints open one at a time

Hint 1
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
20:47
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def maxChunksToSorted(self, arr: List[int]) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[5,4,3,2,1]
Input
[2,1,3,4,4]
Your code is saved on this device.Solution