Plus or Minus Ledger
Medium · 2-D & String DP · about 20 min
An old ledger lost its signs. Each entry in nums was either money in (+) or money out (-), and the book keeper remembers that the final balance was target.
Return how many ways there are to put a + or a - in front of every entry so the entries add up to target. Two ways are different if at least one entry has a different sign, so a 0 entry counts twice (+0 and -0).
0 <= len(nums) <= 20, each entry is a whole number from 0 to 1000.-1000 <= target <= 1000. With no entries the total is 0.
Examples:
count_sign_ways([1, 1, 1, 1, 1], 3) → 5 (pick which one entry gets the minus)
count_sign_ways([0, 0, 1], 1) → 4
Hints
- Process the entries one by one and remember every running total you can be at, with how many ways lead there.
- Each entry turns a total t into t + x and t - x. Add the counts, do not just mark the totals as reachable.
- Start with one way to have total 0, and read the count for the target at the end (0 if it never appeared).
Learn the pattern first: the 2-D & String DP lesson.
More 2-D & String DP problems
- Warehouse Robot Routes (Easy)
- Lightest Hiking Route (Easy)
- Shared Travel Order (Medium)
- Longest Mirror Piece (Medium)
- Two Equal Delivery Vans (Medium)
- Fill the Cargo Bay Exactly (Medium)
- Ways to Pay the Toll (Medium)
- Priced Spelling Fix (Hard)
- Hidden Copies in a Log (Hard)
- File Filter Wildcards (Hard)
- Label Printer Tiles (Hard)