Bank app~25 min2s · 256 MBtarget O(n × total) time, O(total) spaceclassic twin: lc-494knapsack
A bank app reconciles a day's ledger. Each entry is an amount in units. An auditor must label every entry as a credit, which adds it, or a debit, which subtracts it.
The auditor is looking for labellings whose net result equals the balance change the bank reported. Two labellings are different when at least one entry is labelled differently, even when the amounts are equal.
Write count_sign_ways(entries, target).
entries lists the amounts of the ledger entries, whole numbers from 0 upwards.target is the reported net change, which may be negative.target, modulo 1,000,000,007.Input: entries = [1, 1, 2, 3], target = 1
Output: 3Call the entries labelled credit P and the others N. Then P - N = 1 and P + N = 7, so the credits must add up to P = (7 + 1) / 2 = 4. Count the choices of entries that add up to 4. Let ways[s] count the choices among the entries read so far that add up to s, and update the sums downwards.
| after | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| - | 1 | 0 | 0 | 0 | 0 |
| 1 | 1 | 1 | 0 | 0 | 0 |
| 1 | 1 | 2 | 1 | 0 | 0 |
| 2 | 1 | 2 | 2 | 2 | 1 |
| 3 | 1 | 2 | 2 | 3 | 3 |
The last cell is 3. The credit sets are the first 1 with 3, the second 1 with 3, and 1 with 1 with 2.
Input: entries = [1, 2], target = 5
Output: 0The largest possible net change is 3, so 5 is out of reach.
Input: entries = [1, 2], target = 2
Output: 0The total is 3 and the target is 2, so the credits would add up to 2.5, which is not a whole number.
1 ≤ len(entries) ≤ 600 ≤ entries[i] ≤ 50-3000 ≤ target ≤ 3000The total is at most 3,000, so the credits add up to at most 3,000. A table with one entry for each ledger entry and each sum has about 180,000 entries. There are 2^60 labellings, far too many to try.