Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

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

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

Correct answer: A. 12

Excluding the last gives max(3 + 7) = 10; excluding the first gives max(2 + 10) = 12, so 12. Treating it as a line allows 3 + 10 = 13 (adjacent in a circle), 10 is only the first case, and 17 takes adjacent 7 + 10.

More Coding Interview Problems questions

Exams that ask this topic