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