Split parcels into the most balanced shipments
I was asked this
No reports yet. Sign in to say where you were asked it.
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^51 <= 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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
