Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Dynamic programming

Largest sum with no two chosen positions adjacent

Medium · Target 15 minutes · Dynamic programming · Type asked atOptiverJump TradingAmazon

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.

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.