1716. Bundle Shipping Fees
A courier must ship parcels in the order they arrive, where weights[i] is the weight of parcel i. The parcels are split into contiguous bundles, and every parcel goes into exactly one bundle. A bundle is billed at the weight of its heaviest parcel, but the courier grants a loyalty credit of fee for every bundle you book, so the net price of a bundle is its heaviest weight minus fee (the grand total may be negative). Return the minimum possible total net price over all ways of splitting the sequence, as a 64-bit integer. There are 1 to 100000 parcels, each weighing between 1 and 10^9, and 0 <= fee <= 10^9. Aim for O(n) time and O(n) space with a monotonic stack of maximum blocks, each storing its best earlier total, plus a running prefix minimum.
Example 1
- Input:
- weights = [5,1,1,1,5], fee = 3
- Output:
- -2
- Explanation:
Booking five single-parcel bundles bills 5+1+1+1+5 = 13 minus five credits of 3, which is -2, and no grouping does better.
Example 2
- Input:
- weights = [4,9,2], fee = 1
- Output:
- 8
- Explanation:
One bundle bills 9 - 1 = 8, while splitting costs at least 9 because the credit of 1 never repays a split.
Example 3
- Input:
- weights = [7], fee = 10
- Output:
- -3
- Explanation:
A single bundle gives 7 - 10 = -3.
Constraints
1 ≤ n ≤ 105
1 ≤ weights[i] ≤ 109
0 ≤ fee ≤ 109
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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)