
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of Longest Arithmetic Subsequence 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
- for j in range 0 to i - 1, do
- return res
Example (Python)
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))
Input
[1, 4, 7, 10, 13, 20, 16]
Output
6
Advertisements