InferenceAI

Enter at least two characters to search.

Start free

Non-Adjacent Maximum Sum

mediumDynamic Programming25 min25 XP

Choose elements of nums (all non-negative) so that no two chosen elements are adjacent. Return the largest possible sum.

best(i)=max⁡(best(i−1),  best(i−2)+xi)\text{best}(i) = \max\big(\text{best}(i-1),\; \text{best}(i-2) + x_i\big)

Examples

EXAMPLE WALKTHROUGHtake 1 and 3

A guided view of the published example, not a trace of your code.

INPUT[[1,2,3,1]]
TASKnon_adjacent_max_sum()
EXPECTED OUTPUT4

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [1,2,3,1]

Output: 4

Explanation: take 1 and 3

Input: nums = [2,7,9,3,1]

Output: 12

Explanation: take 2, 9, 1

Input: nums = []

Output: 0

Explanation: empty

Hint 1

Track two numbers: the best total including or excluding the previous element.

Topics

DSADynamic ProgrammingPython