1297. Lightest Batch Plan
A courier must deliver n parcels in the fixed order given by the array weights. The parcels are loaded into consecutive batches, and every batch may carry a total weight of at most cap. Dispatching a batch costs the weight of its heaviest parcel. Return the minimum possible total dispatch cost over all ways to cut the sequence into batches. Every parcel weighs at most cap, so a valid plan always exists, and the answer fits in a 64-bit integer. The best cost for a prefix never decreases as the prefix grows, so each segment of a decreasing deque of window maxima only needs its earliest allowed split; keep those candidates in a heap with lazy deletion. Target O(n log n) time.
Example 1
- Input:
- weights = [4,2,3,5], cap = 7
- Output:
- 12
- Explanation:
Splitting into [4, 2], [3] and [5] costs 4 + 3 + 5 = 12, and no valid split is cheaper.
Example 2
- Input:
- weights = [6,6,6], cap = 12
- Output:
- 12
- Explanation:
Two batches of weight 12 and 6 are the fewest allowed, [6, 6] and [6], costing 6 + 6 = 12.
Example 3
- Input:
- weights = [1,2,3], cap = 6
- Output:
- 3
- Explanation:
All three parcels fit in one batch of weight 6, which costs only its heaviest parcel, 3.
Constraints
1 ≤ n ≤ 105
1 ≤ weights[i] ≤ 109
max(weights) ≤ cap ≤ 1015
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 10,000 msC++ 2,500 msJava 5,000 msJavaScript 5,000 msTypeScript 5,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)