KatInterview

Best Haul from a Line of Stalls Without Neighbors

Dynamic ProgrammingAuto-graded · 21 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingarraytake-or-skip

Last updated

Compute the maximum total from a line of non-negative numbers when no two neighboring entries may both be picked, using linear-time dynamic programming.

A market street has a straight line of stalls, and stall i holds a non-negative integer amount of coins, coins[i]. You may collect from any set of stalls, but you may never collect from two stalls that sit directly next to each other (indices i and i + 1).

Return the largest total number of coins you can collect.

Details

  • The street is a straight line, not a loop. The first and last stalls are not neighbors.
  • Collecting from no stalls at all is allowed, so the result is never negative.
  • Return only the maximum total as a single integer. It does not matter which stalls reach that total if several do.
  • If the line is empty, return 0.

Function

Implement max_haul(coins), which takes a list of integers and returns an integer.

Constraints

  • 0 <= len(coins) <= 100000
  • 0 <= coins[i] <= 10000
  • The answer is at most 500,000,000 (at most 50,000 stalls can be chosen).

Examples

Example 1

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

Output: 12

Example 2

Input: max_haul([4, 1, 1, 4])

Output: 8

Example 3

Input: max_haul([])

Output: 0

Hints

Hint 1

When you reach a stall, the only fact about the past that restricts you is whether you collected from the previous stall.

Hint 2

Track two numbers for the prefix seen so far: the best total if the latest stall was collected, and the best total if it was not.

Hint 3

Collecting from the current stall requires the previous one to be skipped; skipping the current one allows either previous state. Update both numbers at the same time from the old values.