Data Structures & AlgorithmsVery hardICPC regional · DP on differences
Problem: What is the length of the longest arithmetic subsequence of [1, 3, 5, 7, 4]? Run the O(n^2) DP code.
Problem: What is the length of the longest arithmetic subsequence of [1, 3, 5, 7, 4]? Run the O(n^2) DP code.
a = [1, 3, 5, 7, 4]
n = len(a)
dp = [dict() for _ in range(n)]
best = 1
for i in range(n):
for j in range(i):
d = a[i] - a[j]
dp[i][d] = max(dp[i].get(d, 1), dp[j].get(d, 1) + 1)
best = max(best, dp[i][d])
print(best)What is printed?- A. 4
- B. 3
- C. 5
- D. 2
Correct answer: A. 4
The subsequence 1, 3, 5, 7 has common difference 2 and length 4. The value 4 at the end does not extend it, and 5 is not reachable.
More Coding Interview Problems questions
- Problem: What is the minimum path sum from the top to the bottom of the triangle [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]], moving to an…
- Problem: How many unordered pairs (i < j) of 1..10 have a sum divisible by 5? Run the code. python a = list(range(1, 11)) print(sum(1 for…
- Problem: Minimum number of operations to reduce x = 5 to 0 by removing a number from either end of [1, 1, 4, 2, 3] (each removal subtracts…
- Problem: How many ordered sequences of 1s and 3s sum to 6? Run the code. python ways = [1] + [0] 6 for v in range(1, 7): for s in (1, 3)…
- Problem: What is the maximum XOR of any contiguous subarray of [8, 1, 2, 12]? Run the brute force. python a = [8, 1, 2, 12] best = 0 for i…
- Problem: Sort [1, 1, 2, 2, 2, 3] by frequency ascending, breaking ties by value ascending. What is printed? python from collections import…