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?- A. 9
- B. 8
- C. 12
- 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
- Problem: How many ways are there to write 12 as a sum of distinct positive integers (partitions into distinct parts)? Run the DP. python…
- Problem: What is the number of trailing zeros of 25 40 125? Run the code. python n = 25 40 125 c = 0 while n % 10 == 0: n //= 10 c += 1…
- Problem: How many integer pairs (x, y) with 1 <= x <= 10 and 1 <= y <= 10 satisfy x y being a perfect cube? Run the code. python…
- Problem: What is the longest run of consecutive integers that all have at least one divisor in common with 30 (gcd greater than 1)…
- Problem: How many integers in [1, 500] are divisible by 4 or by 6 but not by 12? Run the code. python print(sum(1 for x in range(1, 501)…
- Problem: What is the sum of the first 12 terms of the sequence an = n^2 + 1 (n from 1 to 12)? Run the code. python print(sum(n n + 1 for n…