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?- A. 12
- B. 13
- C. 10
- 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
- Problem: How many palindromes of length 4 can be formed over the alphabet {a, b}? Run the code. python from itertools import product…
- Problem: In how many ways can you climb 12 stairs taking 1, 2 or 3 steps at a time (order matters)? Run the DP. python ways = [1] + [0] 12…
- Problem: What is the length of the longest subarray of [1, 2, -3, 3, -1, -2] whose sum is zero? Run the prefix-sum code. python a = [1, 2…
- Problem: How many integers in [1, 100] are sums of two positive cubes? Run the code. python print(len({a 3 + b 3 for a in range(1, 5) for…
- Problem: How many distinct sums of two different elements of [1, 2, 4, 8] are there? Run the code. python from itertools import…
- Problem: How many ways are there to place 2 non-attacking rooks on a 4 x 4 board? Run the code. python from itertools import combinations…