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?- A. 12
- B. 10
- C. 13
- 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
- Problem: How many ways tile a 1 x 4 strip with 1 x 1 squares and 1 x 2 dominoes? Run the code. python f = [1, 1] for in range(3)…
- Problem: How many trailing zero bits does 40 have in binary? Run the code. python print((40 & -40).bitlength() - 1) What is printed?
- Problem: How many pairs (i < j) of [2, 4, 6, 8] have gcd exactly 2? Run the code. python from itertools import combinations from math…
- Problem: Starting at (0,0) in the grid below, how many cells are reachable by 4-directional moves through '.' cells? Run the BFS. python…
- Problem: What is the minimum number of coins from {1, 5, 10, 25} summing to 63? Run the DP. python INF = 10 9 d = [0] + [INF] 63 for v in…
- Problem: Climbing stairs 0 to 5 with steps of 1 or 2, but stair 3 is broken and cannot be stood on. How many ways are there to reach stair…