KatInterview

Best Haul from a Row of Cash Stations

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingarraysoptimization

Last updated

Tests one-dimensional dynamic programming: pick values from a sequence so no two neighbors are both chosen, maximizing the total.

Cash Stations in a Row

A line of cash stations is laid out one after another. The list amounts gives the cash stored at each station, in order.

Because of a safety rule, if you collect from a station you may not collect from the station directly before it or directly after it. In other words, no two collected stations may be neighbors in the list. You are free to skip as many stations as you like.

Compute the largest total amount of cash you can collect while obeying this rule.

Input

  • amounts: a list of integers, where amounts[i] is the cash at station i.

Output

  • A single integer: the maximum total that can be collected with no two neighboring stations both chosen.

Notes

  • Stations are neighbors only if their indices differ by exactly 1.
  • Choosing no stations at all is allowed and yields a total of 0. This matters only if every amount is non-positive, which falls outside the stated constraints.

Constraints

  • 1 <= len(amounts) <= 10^5
  • 0 <= amounts[i] <= 10^9

Examples

Example 1

Input: max_cash_collected([1, 2, 3, 1])

Output: 4

Example 2

Input: max_cash_collected([2, 7, 9, 3, 1])

Output: 12

Hints

Hint 1

Look at the last station only. Either you collect from it or you don't. What does each choice tell you about the stations before it?

Hint 2

If you collect from station i, you must ignore station i-1, so the best total is amounts[i] plus the best result over stations 0..i-2. If you skip it, the best total is the best result over stations 0..i-1.

Hint 3

Each step needs only the best results for the previous two prefixes, so two rolling variables are enough instead of a whole table. Start both at 0 so short lists work with no special case.