Ctrl K

Sorting Batches With Repeats

Hard
Boxes stand in a row on a conveyor, and their weights are given in the array weights (weights may repeat). The row is cut into several contiguous batches; the boxes inside each batch are sorted by weight independently of the others, and the batches are put back in their original order. The whole row must end up sorted in non-decreasing order. Return the largest number of batches you can cut the row into.
Example 1
weights=[3, 1, 2, 5, 4, 4] → 2

Split into [3, 1, 2] and [5, 4, 4]: after sorting each part we get [1, 2, 3, 4, 4, 5]. Any other cut breaks the order; for example, 5 has to end up after both 4s.

Example 2
weights=[2, 2, 1, 3] → 2

The 1 has to move in front of both 2s, so the first three boxes form one batch and 3 forms another.

Example 3
weights=[7, 7, 7] → 3

Equal weights are already in order, so every box can be its own batch.

Constraints
  • 1 ≤ len(weights) ≤ 10⁵
  • 0 ≤ weights[i] ≤ 10⁸
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFix the Middle of the Line MediumMost Pieces Sorted Separately MediumOutclassed Heroes MediumLargest Number From Two Rows HardRaising by Ranges Hard
loading Python…
Input
weights=[3, 1, 2, 5, 4, 4]
Expected
2

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