Skip to contentKEEP THE CRAFTTHE SANCTUARY

Best Non-Adjacent Sum for Every Prefix

Fill the house-robber DP table: the best non-adjacent total from the first i values.

The problem

Implement non_adjacent_prefix_states(values). values holds nonnegative integers. You may pick any values as long as no two picked values sit next to each other. Return a list dp of length len(values) + 1 where dp[i] is the largest total you can pick from the first i values (values[:i]); dp[0] is 0. For example, [2, 7, 9, 3, 1] gives [0, 2, 7, 11, 11, 12]: from the first three values the best pick is 2 + 9 = 11. values may be empty, which gives [0].

Starter code

def non_adjacent_prefix_states(values):
    pass

Public examples

  1. values = [2, 7, 9, 3, 1]gives[0, 2, 7, 11, 11, 12]
  2. values = [5, 1]gives[0, 5, 5]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.