Longest Subsequence such that difference between adjacent elements is either A or B
Given an array arr of size N, and two integers A and B. The task is to find the length of the longest subsequence with the difference between adjacent elements as either A or B.
Example:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input : arr[]={ 5, 5, 5, 10, 8, 6, 12, 13 }, A=0, B=1
Output : 4
Explanation : Maximum length subsequence is {5,5,5,6}Input : arr[] = {4, 6, 7, 8, 9, 8, 12, 14, 17, 15}, A=2, B=1
Output : 6
Approach: On taking a closer look at the problem, the problem is similar to Longest Consecutive Subsequence. The only difference between them is now we have to count for the elements with differences A or B instead of 1. Now, to solve this problem, follow the below steps:
- Create a map, which will store each element as the key, and the length of the longest subsequence ending with arr[i] as the value.
- Now, traverse the array arr, and for each element arr[i]:
- Search for arr[i]-A, arr[i]+A, arr[i]-B, arr[i]+B in the map.
- If they are present find the maximum of all and +1 in that to get the maximum length of subsequence.
- Find the maximum value in the map, and return it as the answer
Below is the implementation of the above approach.
C++
// C++ code for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the length of// longest common subsequence with// difference between the consecutive// element is either A or Bint maxSubsequence(vector<int>& arr, int A, int B){ int N = arr.size(); int ans = 1; // Map to store the length of longest subsequence // ending with arr[i] unordered_map<int, int> mp; for (int i = 0; i < N; ++i) { int aa = 1; // If arr[i]-A exists if (mp.count(arr[i] - A)) { aa = mp[arr[i] - A] + 1; } // If arr[i]+A exists if (mp.count(arr[i] + A)) { aa = max(aa, mp[arr[i] + A] + 1); } // If arr[i]-B exists if (mp.count(arr[i] - B)) { aa = max(aa, mp[arr[i] - B] + 1); } // If arr[i]+B exists if (mp.count(arr[i] + B)) { aa = max(aa, mp[arr[i] + B] + 1); } mp[arr[i]] = aa; ans = max(ans, mp[arr[i]]); } return ans;} // Driver Codeint main(){ vector<int> arr = { 5, 5, 5, 10, 8, 6, 12, 13 }; int A = 0, B = 1; cout << maxSubsequence(arr, A, B); return 0;} |
4
Time Complexity: O(N)
Auxiliary Space: O(N)


