← Questions

Split parcels into the most balanced shipments

0
AmazonCoding

A coding interview question asked at Amazon. It tests greedy, arrays and dynamic programming.

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.

Clarifying questions

  • For an empty line, is the answer 0?
  • Is "strictly less" exact, so a shipment ending on a tie with its maximum is not balanced?
  • Does a one-parcel shipment ever count? (No: its last parcel is its maximum.)
  • Should we return the cuts too?

What a strong answer covers

  • Defines best[i] as the most balanced shipments for the first i parcels, or "impossible".
  • A shipment ending at parcel i - 1 is balanced exactly when it starts at or before the nearest earlier parcel that is strictly heavier. A monotonic stack finds that index for every parcel.
  • So best[i] is 1 plus the best value among the allowed start points. A running prefix maximum of best gives it in O(1). The whole thing is O(n).
  • Keeps "impossible" prefixes out of the maximum.
  • Tests all three examples, a strictly increasing line, a single parcel, and equal weights.

Follow-ups

  • Return the cuts.
  • Find the fewest balanced shipments instead.
  • A shipment is balanced when its first parcel is lighter than its maximum.
  • Each shipment also has a maximum total weight.

Where it's asked

What it tests

greedy · arrays · dynamic programming

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