Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Dynamic programming

Largest sum with no two chosen positions adjacent

Medium · Target 15 minutes · Dynamic programming· Type asked at

Given an array nums of non-negative integers, choose a subset of positions such that no two chosen positions are adjacent, and return the largest possible sum of the chosen values. Choosing nothing is allowed, so the answer is never negative.

Examples

InputOutputWhy
nums = [1, 2, 3, 1]4Positions 0 and 2: 1 + 3.
nums = [2, 7, 9, 3, 1]12Positions 0, 2 and 4: 2 + 9 + 1. Taking 7 and 3 gives only 10.
nums = [4, 1, 1, 4, 2, 1]9Positions 0, 3 and 5.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ nums[i] ≤ 10⁴

Hints

Hint 1

Greedy fails. Taking the largest value first breaks on [2, 7, 9, 3, 1], where the greedy choice of 9 then blocks nothing useful, but on [5, 6, 5] it blocks both fives.

Hint 2

Think about the last position only. Either you take it or you do not, and each choice leaves a smaller version of the same problem.

Hint 3

If you take position i you cannot have taken i−1, so you add nums[i] to the best answer up to i−2. If you skip it, you keep the best answer up to i−1.

Hint 4

That recurrence only ever looks two steps back, so the whole table collapses into two variables.

Where people lose marks

  • Reaching for greedy. It survives the first example and dies on the second, which is exactly how it gets through a first-round screen and fails the on-site.
  • Assuming the chosen positions must alternate. On [5, 1, 1, 5] the answer takes positions 0 and 3, which are three apart.
  • Initialising the two carried values to nums[0] and nums[1]. It works only if n ≥ 2, and the off-by-one is easy to get wrong. Initialise both to 0 and let the loop handle every position uniformly.
  • Writing the O(n)-space table and stopping there. It is correct, and leaving the O(1) version unsaid costs you the follow-up.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.