1356. Safest Box Stack

A warehouse stacks all n boxes into one tower, in an order you choose. Box i has weight weights[i] and can carry strengths[i] units of load. The risk of a box is the total weight of all boxes above it minus its own strength, so the top box has a risk of minus its strength, and a negative risk means spare capacity. Return the smallest value that the largest risk in the tower can take over all possible stacking orders, as a 64-bit integer; the answer may be negative. A box with a smaller sum of weight and strength should sit higher in the tower. Totals can reach about 10^14, so use 64-bit arithmetic. Aim for O(n log n) time and O(n) space.

Example 1

Input:
weights = [4,2,3], strengths = [1,6,2]
Output:
2
Explanation:

Putting box 0 (weight 4), then box 2 (weight 3), then box 1 on the bottom gives risks -1, 2 and 1, so the largest risk is 2 and no order does better.

Example 2

Input:
weights = [5], strengths = [9]
Output:
-9
Explanation:

A single box has nothing above it, so its risk is minus its strength, -9.

Example 3

Input:
weights = [1,1], strengths = [1,1]
Output:
0
Explanation:

The top box has risk -1 and the bottom box carries weight 1 with strength 1, so its risk is 0.

Constraints

1 ≤ n ≤ 105

weights.length == strengths.length

1 ≤ weights[i], strengths[i] ≤ 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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…