Ctrl K

Most Pieces Sorted Separately

Medium
The array order of length n holds each of the numbers 0 to n − 1 exactly once. The array is cut into several contiguous pieces, each piece is sorted on its own, and the pieces are then glued back together in the same order. The result must be the array sorted in ascending order. Return the largest number of pieces the array can be cut into this way.
Example 1
order=[2, 0, 1, 4, 3, 5] → 3

Cut it into [2, 0, 1], [4, 3] and [5]: sorting the pieces gives 0 1 2 3 4 5. More pieces are impossible; for instance, 2 cannot be separated from 0 and 1.

Example 2
order=[0, 1, 2] → 3

The order is already correct, so each element can be its own piece.

Example 3
order=[3, 1, 2, 0] → 1

The 0 sits at the very end and the 3 at the very start, so they cannot be separated, leaving one piece.

Constraints
  • 1 ≤ n ≤ 10
  • order is a permutation of 0, 1, …, n − 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFix the Middle of the Line MediumOutclassed Heroes MediumSorting Batches With Repeats HardConvoys at the Finish MediumTree of Leaf Products Medium
loading Python…
Input
order=[2, 0, 1, 4, 3, 5]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 127 tests on the server, hidden ones included.