Payments app~30 min2s · 256 MBtarget O(d × 2^n × n) for d divisors of the total time, O(2^n) spaceclassic twin: lc-698backtracking
A payments app settles a list of payouts to a merchant. Each payout has an amount in units. The bank accepts transfers in batches, and it wants every batch of a run to have exactly the same total.
Every payout must go in exactly one batch, and a payout can not be split. The team wants as many equal batches as possible, because small batches clear faster.
Write most_equal_batches(amounts).
amounts is a list of whole numbers, the payouts.Input: amounts = [4,3,2,3,5,2,1]
Output: 4The total is 20. The solution tries the number of batches from the most to the fewest. A number of batches k needs a batch total of 20 / k that is a whole number and at least the biggest amount.
Batches k |
Batch total | Result |
|---|---|---|
| 7 | none | 20 does not divide by 7 |
| 6 | none | 20 does not divide by 6 |
| 5 | 4 | the amount 5 is more than 4 |
| 4 | 5 | search: 5, then 4 + 1, 3 + 2, 3 + 2 |
The four batches are 5, 4 + 1, 3 + 2 and 3 + 2, so the answer is 4.
Input: amounts = [5,5,5]
Output: 3Each payout is its own batch of 5.
Input: amounts = [6,10]
Output: 1Two batches would need 8 each, and no payout fits. The only split is one batch of 16.
1 ≤ len(amounts) ≤ 141 ≤ amounts[i] ≤ 100Giving each payout one of k batch numbers makes k^14 assignments, and for k = 4 that is 268,435,456. But 14 payouts have only 16,384 subsets. A search that remembers the subsets that failed visits each at most once.