Data Structures & AlgorithmsHardProduct Company SDE · DP round

Problem: What is the maximum sum of non-adjacent elements of [3, 2, 7, 10]? Run the DP.

Problem: What is the maximum sum of non-adjacent elements of [3, 2, 7, 10]? Run the DP.
a = [3, 2, 7, 10]
inc = exc = 0
for x in a:
    inc, exc = exc + x, max(inc, exc)
print(max(inc, exc))
What is printed?
  1. A. 12
  2. B. 10
  3. C. 13
  4. D. 17

Correct answer: C. 13

Choosing 3 and 10 gives 13, which beats 2 and 10 (12) and 3 and 7 (10). The DP tracks the best sum with the last element taken and not taken.

More Coding Interview Problems questions

Exams that ask this topic