# Program to find length of longest arithmetic subsequence with constant difference in Python

Suppose we have a list of numbers nums and another value diff, we have to find the length of the longest arithmetic subsequence where the difference between any consecutive numbers in the subsequence is same as diff.

So, if the input is like nums = [-1, 1, 4, 7, 2, 10] diff = 3, then the output will be 4, because, we can pick the subsequence like [1, 4, 7, 10].

To solve this, we will follow these steps −

• seen := an empty dictionary, default value is 0 when key is not present
• mx := 0
• for each x in nums, do
• if x - diff is in seen, then
• seen[x] := seen[x - diff] + 1
• otherwise,
• seen[x] := 1
• mx := maximum of mx and seen[x]
• return mx

## Example

Let us see the following implementation to get better understanding −

from collections import defaultdict
def solve(nums, diff):
seen = defaultdict(int)
mx = 0
for x in nums:
if x - diff in seen:
seen[x] = seen[x - diff] + 1
else:
seen[x] = 1
mx = max(mx, seen[x])
return mx

nums = [-1, 1, 4, 7, 2, 10]
diff = 3
print(solve(nums, diff))

## Input

[-1, 1, 4, 7, 2, 10], 3

## Output

4

Updated on: 19-Oct-2021

131 Views