- Related Questions & Answers
- Program to find length of longest Fibonacci subsequence from a given list in Python
- Program to find length of longest alternating subsequence from a given list in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Longest Arithmetic Subsequence of Given Difference in C++
- Program to find length of longest sign alternating subsequence from a list of numbers in Python
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest common subsequence of three strings in Python
- Program to find length of longest common subsequence in C++
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest interval from a list of intervals in Python
- C++ Program to Find the Longest Increasing Subsequence of a Given Sequence
- Program to find length of longest sublist with given condition in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

- for j in range 0 to i - 1, do
- return res

Let us see the following implementation to get better understanding −

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))

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

6

Advertisements