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?
  1. A. 4
  2. B. 3
  3. C. 5
  4. 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

Exams that ask this topic