- Related Questions & Answers
- Arithmetic Mean in C programming
- Print longest palindrome word in a sentence in C Program
- What is the difference between Enumeration interface and enum in Java?
- What is the difference between throw e and throw new Exception(e) in catch block in java?
- What is the difference between selenium and automation?
- What is difference between selenium 1 and Selenium 2
- Difference between import and package in Java?
- Difference between the byte stream and character stream classes in Java?
- Arrange first N natural numbers such that absolute difference between all adjacent elements > 1?
- What is difference between onCreate() and onStart() on Android?
- What is the difference between selenium WebDriver and TestNG?
- What is difference between selenium 2 and selenium 3?
- C Program for Difference between sums of odd and even digits?
- What's the difference between sizeof and alignof?
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?

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

Let us see the following implementation to get better understanding −

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; } };

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

4

Advertisements