This problem asks us to find the longest subsequence (not subarray) where the difference between consecutive elements is constant. The subsequence does not need to be contiguous, which makes it harder than finding arithmetic subarrays.
An arithmetic subsequence is fully described by two things: where it ends and its common difference. Once both are fixed, extending the subsequence means finding an earlier element that sits exactly one step (the common difference) below the current one. That framing drives both approaches below.
2 <= nums.length <= 1000. With n up to 1,000, an O(n^2) solution runs in about 1 million operations. O(n^3) would be 1 billion, which is too slow for a comfortable margin.0 <= nums[i] <= 500. Values are non-negative and bounded, so the common difference falls between -500 and 500. The difference therefore fits in a normal int, and a subsequence can be at most 1,000 long, so no count overflows.A pair of indices already determines a common difference. Pick two indices i and j with i < j, set d = nums[j] - nums[i], then walk forward from j + 1 and greedily take the next element equal to the last value plus d.
The greedy forward scan is safe here because the next value the chain needs, last + d, is a single fixed number. Any element equal to it extends the chain by one, and taking the earliest one leaves the most array left to extend further. So scanning left to right and grabbing the first match never undercounts.
(i, j) with i < j, compute the common difference d = nums[j] - nums[i].last = nums[j] and a running length of 2.j + 1 to the end. Whenever an element equals last + d, increment the length and move last forward to it.Input:
We start with maxLen = 2 and try every pair.
maxLen becomes 3.Every remaining pair gives length 2, so the answer is 3.
The forward scan repeats work: every pair rescans the tail of the array. The next approach removes that scan by storing, for each index and each common difference, how long a chain already ends there. Extending then becomes a single lookup.
If we already know the longest arithmetic subsequence ending at index j with common difference d, then any later index i with nums[i] - nums[j] == d extends it by one in O(1) time. We do not need to rescan anything.
Define dp[i] as a hash map where dp[i][d] holds the length of the longest arithmetic subsequence that ends at index i and has common difference d. Iterating j over all earlier indices for each i fills these maps, and the largest value across all of them is the answer.
dp, where dp[i] maps each common difference to the length of the longest arithmetic subsequence ending at index i.i from 1 to n-1:j from 0 to i-1:diff = nums[i] - nums[j].dp[j] contains diff, set dp[i][diff] = dp[j][diff] + 1.dp[i][diff] = 2 (the pair nums[j], nums[i]).