Parcel-delivery app~30 min2s · 256 MBtarget O(n × total) time, O(total) spaceclassic twin: lc-1049knapsack
A building-supplies delivery app feeds stones to a crusher, one pair at a time. The operator picks any two stones and crushes them together. If they weigh the same, both turn to dust. Otherwise the lighter one is gone, and the heavier one keeps its weight minus the lighter weight.
The operator keeps going until at most one stone is left. The app wants to know the smallest weight that can remain.
Write smallest_leftover(stones).
stones lists the weights of the stones, whole numbers of kilograms.|a - b|, or nothing when the weights are equal.Input: stones = [3, 8, 5, 4]
Output: 2Every stone ends up on one of two sides of the final difference. So the answer is total - 2 × best, where best is the heaviest group of stones that weighs at most half of the total. Here the total is 20 and half is 10. Let reachable[s] say whether some group of the stones read so far weighs exactly s.
| after | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| - | yes | no | no | no | no | no | no | no | no | no | no |
| 3 | yes | no | no | yes | no | no | no | no | no | no | no |
| 8 | yes | no | no | yes | no | no | no | no | yes | no | no |
| 5 | yes | no | no | yes | no | yes | no | no | yes | no | no |
| 4 | yes | no | no | yes | yes | yes | no | yes | yes | yes | no |
The heaviest reachable sum up to 10 is 9. The answer is 20 − 2 × 9 = 2. The groups are 5 and 4 against 3 and 8.
Input: stones = [5]
Output: 5One stone cannot be crushed against another.
Input: stones = [4, 4, 4, 4]
Output: 0The groups 4 + 4 and 4 + 4 weigh the same, so everything turns to dust.
1 ≤ len(stones) ≤ 1001 ≤ stones[i] ≤ 100The total is at most 10,000, so half of it is at most 5,000. A table with one entry for each stone and each sum has about 500,000 entries. Trying every order of crushing is far larger than that, because each turn has many pairs to choose from.