Program to find length of longest arithmetic subsequence of a given list in Python


Suppose we have a list of numbers called nums, we have to find the length of the longest arithmetic subsequence. As we know a sequence S[i] is an arithmetic sequence when S[i+1] - S[i] have the same value for every i in range (0 ≤ i < Size of S - 1).

So, if the input is like nums = [1, 4, 7, 10, 13, 20, 16], then the output will be 6, the subsequence [1, 4, 7, 10, 13, 16] is an arithmetic because the difference between each consecutive element is 3.

To solve this, we will follow these steps −

  • n := size of arr
  • if n <= 1, then
    • return n
  • res := 0
  • dp := an empty map, by default it will store 1 when key is not found
  • for i in range 1 to n - 1, do
    • for j in range 0 to i - 1, do
      • diff := arr[i] - arr[j]
      • dp[i, diff] := dp[j, diff] + 1
      • res := maximum of res and dp[i, diff
  • return res

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

from collections import defaultdict
class Solution:
   def solve(self, arr):
      n = len(arr)
      if n <= 1:
         return n
      res = 0
      dp = defaultdict(lambda: 1)
      for i in range(1, n):
         for j in range(i):
            diff = arr[i] - arr[j]
            dp[i, diff] = dp[j, diff] + 1
            res = max(res, dp[i, diff])
      return res
ob = Solution()
nums = [1, 4, 7, 10, 13, 20, 16]
print(ob.solve(nums))

Input

[1, 4, 7, 10, 13, 20, 16]

Output

6

Updated on: 12-Dec-2020

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements