Parcel-delivery app~25 min2s · 256 MBtarget O(n × total) time, O(total) spaceclassic twin: lc-416knapsack
A delivery app loads a batch of parcels onto two vans. A van's load is the total weight of its parcels, in kilograms. The dispatcher wants both vans to carry exactly the same load, so that neither is overloaded.
Every parcel goes on one van or the other, and no parcel can be cut.
Write can_split_evenly(weights).
weights lists the weight of each parcel, whole numbers of kilograms.true when the parcels can be split between two vans with equal total weights, and false otherwise.Input: weights = [3, 1, 4, 2]
Output: trueThe total is 10, so each van must carry 5. Let reachable[s] say whether some choice of the parcels read so far weighs exactly s. Start with reachable[0] = yes: the empty choice. For each parcel of weight w, go through the sums downwards from 5 to w, and set reachable[s] when reachable[s - w] is already set.
| after | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| - | yes | no | no | no | no | no |
| 3 | yes | no | no | yes | no | no |
| 1 | yes | yes | no | yes | yes | no |
| 4 | yes | yes | no | yes | yes | yes |
| 2 | yes | yes | yes | yes | yes | yes |
The last cell is yes. The vans carry 3 + 2 and 1 + 4.
Input: weights = [3, 3, 4]
Output: falseThe total is 10, so each van must carry 5. The possible loads are 0, 3, 4, 6, 7 and 10, and 5 is not among them.
Input: weights = [2, 2, 3]
Output: falseThe total is 7, which is odd. Two vans cannot carry equal loads.
1 ≤ len(weights) ≤ 2001 ≤ weights[i] ≤ 100The total is at most 20,000, so half of it is at most 10,000. A table with one entry for each parcel and each sum has about 2 million entries. Trying every choice of parcels is 2^200 choices, which no machine can finish.