- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

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

# Longest Arithmetic Subsequence of Given Difference in C++

Suppose we have an integer array arr and an integer difference, we have to find the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence is same as the difference. So if the input is like [1,5,7,8,5,3,4,2,1] and difference is -2, then the output will be − 4, as the longest arithmetic sequence is [7,5,3,1]

To solve this, we will follow these steps −

- Define a map m
- n := size of array arr, set ans := 0
- for i in range 0 to n – 1
- x := arr[i]
- m[x] := 1 + m[x - d]
- ans := max of and m[x]

- return ans

## Example

Let us see the following implementation to get a better understanding −

#include <bits/stdc++.h> using namespace std; class Solution { public: int longestSubsequence(vector<int>& arr, int d) { int n = arr.size(); map <int,int> m; int ans = 0; for(int i =0;i<n;i++){ int x = arr[i]; m[x] = 1 + (m[x-d]); ans = max(ans,m[x]); } return ans; } }; main(){ vector<int> v1 = {1,5,7,8,5,3,4,2,1}; Solution ob; cout <<ob.longestSubsequence(v1, -2); }

## Input

[1,5,7,8,5,3,4,2,1] -2

## Output

4

- Related Articles
- Program to find length of longest arithmetic subsequence with constant difference in Python
- Program to find length of longest arithmetic subsequence of a given list in Python
- Longest Common Subsequence in C++
- Longest Harmonious Subsequence in C++
- Longest Palindromic Subsequence in C++
- Arithmetic Slices II - Subsequence in C++
- Number of Longest Increasing Subsequence in C++
- Length of Longest Fibonacci Subsequence in C++
- Longest Arithmetic Sequence in C++
- C++ Program to Find the Longest Increasing Subsequence of a Given Sequence
- Longest Uncommon Subsequence II in C++
- Longest Uncommon Subsequence I in C++
- Longest Continuous Increasing Subsequence in C++
- C++ Program for Longest Common Subsequence
- Longest Common Subsequence

Advertisements