← Questions

Split parcels into the most balanced shipments

0
AmazonCoding

Parcels sit on a conveyor in a fixed order, and weights[i] is the weight of the i-th parcel. You must cut the line into contiguous shipments so that every parcel belongs to exactly one shipment.

A shipment is balanced if the weight of its last parcel is strictly less than the heaviest weight in that shipment.

Implement max_balanced_shipments(weights: list[int]) -> int. It returns the largest number of shipments in a split where every shipment is balanced. If no such split exists, it returns 0.

Constraints

  • 0 <= n <= 10^5
  • 1 <= weights[i] <= 10^9
  • Aim for O(n) time.

Example 1

weights = [4, 9, 2, 7, 7, 1]
output  = 2

One optimal split is [4, 9, 2] | [7, 7, 1]. Both shipments end lighter than their heaviest parcel. Three shipments are impossible.

Example 2

weights = [5, 1, 3, 2, 4]
output  = 1

[5, 1] | [3, 2, 4] fails because the second shipment ends on its heaviest parcel. The only valid split is the whole line as one shipment.

Example 3

weights = [1, 2, 3]
output  = 0

Any shipment that ends with the 3 has 3 as its maximum, so it can never be balanced.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding