Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the maximum sum of a subsequence (not necessarily contiguous) of [4, -2, 5, -1, 3] with no two chosen elements adjacent? Run the DP.

Problem: What is the maximum sum of a subsequence (not necessarily contiguous) of [4, -2, 5, -1, 3] with no two chosen elements adjacent? Run the DP.
a = [4, -2, 5, -1, 3]
inc = exc = 0
for x in a:
    inc, exc = exc + x, max(inc, exc)
print(max(inc, exc))
What is printed?
  1. A. 9
  2. B. 8
  3. C. 12
  4. D. 4

Correct answer: C. 12

The DP takes 4, 5 and 3 (indices 0, 2, 4), total 12. Kadane's contiguous maximum is 9, skipping the first element gives 5 + 3 = 8, and stopping after the first choice gives 4.

More Coding Interview Problems questions

Exams that ask this topic