
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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]
- if x - diff is in seen, then
- 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
- Related Questions & Answers
- Program to find length of longest arithmetic subsequence of 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
- Program to find length of longest fibonacci subsequence in Python
- Longest Arithmetic Subsequence of Given Difference in C++
- Program to find length of longest circular increasing subsequence 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 common subsequence of three strings in Python
- Program to find out the length of longest palindromic subsequence using Python
- Program to find length of longest increasing subsequence with at least k odd values in Python
- 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
Advertisements