KatInterview

Best Haul from a Row of Stalls Without Adjacent Picks

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingarraysnon-adjacent-selection

Last updated

Pick values from a row so that no two chosen positions are neighbors, maximizing the total, which tests recognizing and implementing a simple one-dimensional dynamic programming recurrence.

Stall Row Collection

A market has a row of stalls, numbered from left to right. Stall i offers a prize worth prizes[i] points. You walk along the row and may collect the prize from any stall you like, but a guard watches every stall you collect from, so you are not allowed to collect from two stalls that sit next to each other (indices i and i + 1).

You may skip as many stalls as you want, including all of them.

Write a function that returns the largest total number of points you can collect while obeying this rule.

Details

  • Stalls that are not adjacent (for example indices 0 and 2) may both be chosen.
  • If there are no stalls, the answer is 0.
  • Every prize is non-negative, so collecting nothing is always allowed and contributes 0.
  • The function returns a single integer, the maximum achievable total.

Constraints

  • 0 <= len(prizes) <= 10^5
  • 0 <= prizes[i] <= 10^4

Examples

Example 1

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

Output: 4

Example 2

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

Output: 12

Example 3

Input: max_non_adjacent_haul([])

Output: 0

Example 4

Input: max_non_adjacent_haul([5])

Output: 5

Hints

Hint 1

Look at just the last stall. Either you collect from it or you do not. What does each choice imply about the stall before it?

Hint 2

Let best(i) be the top total using only the first i stalls. Then best(i) = max(best(i-1), best(i-2) + prizes[i-1]).

Hint 3

The recurrence only reads the previous two results, so two variables are enough instead of a full table.