Best Haul Without Neighbours

MediumDynamic Programming≈ 30 min

A row of market stalls is closing, and each stall offers its leftover stock for free: stall i has values[i] worth of goods. Stall keepers who stand next to each other share a till, so you may never take from two neighbouring stalls. Return the most you can collect.

Examples

text
values = [1, 2, 3, 1]      →  4
values = [2, 7, 9, 3, 1]   →  12
values = [5]               →  5
values = [2, 1, 1, 2]      →  4

In the second example the stalls worth 2, 9 and 1 are never next to each other: 12. In the last, the best is the first and the last stall, though two stalls in between are skipped.

Constraints

  • Between 0 and 20,000 stalls, each worth between 0 and 10,000.
  • Aim for O(n) time and O(1) memory.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.