Payments app~35 min2s · 256 MBtarget O(2^n × n) time, O(2^n) spaceclassic twin: lc-698dp
A payments app settles money with banks in batches. Operations wants to send the day's n batches in k settlement runs, and every run must carry the same total amount.
A batch cannot be split: it goes into one run as a whole. Amounts are in units, and the day can have at most 16 batches. Tell operations whether such a split exists.
Write can_partition(batches, k).
batches[i] is the amount of batch i, a whole number of units.k runs. A run holds at least one batch.true if all k runs can have the same total, and false if they cannot.Input: batches = [3, 1, 2, 2], k = 2
Output: trueThe total is 8, so each run must carry 4. Let filled[mask] be the amount in the run that is still open, after the batches in the mask are placed. It is -1 if they cannot be placed without overfilling a run. Bit j of the mask stands for batch j.
| Step | What happens | filled |
|---|---|---|
| [2] | Nothing is placed | filled[0000] = 0 |
| [4] | Batch 0 (3) goes in, and then batch 1 (1) | filled[0001] = 3, filled[0011] = 0 |
| [4] | Batches 0 and 2 (3 + 2) overfill a run, so they cannot be placed in either order | filled[0101] = -1 |
| [4] | Batches 2 and 3 (2 + 2) fill a run and close it | filled[1100] = 0 |
| [5] | All four placed, no run left open | filled[1111] = 0, so true |
The runs are {3, 1} and {2, 2}.
Input: batches = [4, 1, 1], k = 3
Output: falseThe total is 6, so each run must carry 2. The batch of 4 is larger than that.
Input: batches = [2, 2, 3], k = 2
Output: falseThe total is 7. It cannot be shared by 2 runs.
1 ≤ n ≤ 16 and 1 ≤ k ≤ n1 ≤ batches[i] ≤ 10^6Giving each of 16 batches to one of k runs can be done in k^16 ways. For k = 4 that is 4,294,967,296, which is too slow to try.
The set of batches already placed has only 2^16 = 65,536 possibilities. A table with one entry for each set, and 16 moves from each, is about a million steps.