Problem 459
Longest Arithmetic Subsequence
Medium · 20 pts · Array, Dynamic Programming, Hash Table
Problem
Find the length of the longest subsequence of the array that forms an arithmetic sequence, meaning the difference between consecutive chosen elements is always the same (the difference may be zero or negative). A subsequence keeps the original order but may skip elements. Any two elements form an arithmetic sequence of length 2. For each position i and each difference d, track the longest arithmetic subsequence ending at i with difference d.
Input
First line: N. Second line: N integers.
Output
Print the length of the longest arithmetic subsequence.
Constraints
2 <= N <= 1000; 0 <= A[i] <= 500
Example input
5 9 4 7 2 10
Example output
3
Explanation
In 9 4 7 2 10, the subsequence 4 7 10 has a constant difference of 3, and no arithmetic subsequence is longer, so the answer is 3.