All problems
1163HardArrayStackGreedySortingMonotonic Stack

Cutting the Row Into the Most Blocks

Tracked in this browser only
Write code

Trains the technique from

LeetCode 768Max Chunks To Make Sorted II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A row holds the weights weights, and weights may repeat. Cut the row into blocks of neighbouring crates so that sorting each block on its own leaves the whole row in non-decreasing order.

Return the largest number of blocks such a cut can use.

Examples

Example 1

Input
weights = [1, 3, 2, 4]
Output
3

Cut after the first crate and after the third. The middle block of 3 and 2 sorts into 2 and 3, and the whole row comes out in order.

Example 2

Input
weights = [2, 3, 1, 4]
Output
2

The 1 has to end up before both the 2 and the 3, so those three crates must share a block. Cutting after them gives two blocks.

Example 3

Input
weights = [1, 1]
Output
2

Both crates weigh the same, so the cut between them is allowed and each is its own block.

Constraints

  • 1 <= weights.length <= 2000
  • 0 <= weights[i] <= 10^8

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def max_chunks_to_sorted(weights: list[int]) -> int:
Java
public int maxChunksToSorted(int[] weights)
September 7
Apply