Longest subsequence such that difference between adjacent elements is K
Given an array arr[] of size N and an integer K, the task is to find the longest subsequence such that the difference between adjacents is K.
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[]={1, 2, 3, 4, 5, 3, 2}, K=1
Output: 6
Explanation: The longest subsequence with the difference between the adjacent elements as 1 is: {1, 2, 3, 4, 3, 2}Input: arr[]={1, 2, 3, 2, 3, 7, 2, 1}, K=2
Output: 3
Approach: The given problem can be solved using Dynamic Programming. The idea is to store the length of the longest subsequence having a difference K between adjacents ending after including the current element. Create an unordered map mp where mp[i] represents the maximum length of subsequence which includes integer i.
So, the relation to get the maximum length subsequence can be written as:
mp[i] = 1 + max(mp[i – K], mp[i + K])
The maximum integer stores in the map mp is the required 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 longest// subsequence such that difference// between adjacent elements is Kint longestSubsequence(vector<int>& arr, int K){ // Stores length of longest // subsequence in a map unordered_map<int, int> mp; // Variable to store the maximum // length of subsequence int mx = 1; // Loop to iterate through the // given array for (auto x : arr) { mp[x] = 1; // If (x - K) exists if (mp.count(x - K)) { mp[x] = 1 + mp[x - K]; } // if (x + K) exists if (mp.count(x + K)) { mp[x] = max(mp[x], 1 + mp[x + K]); } mx = max(mx, mp[x]); } // Return Answer return mx;} // Driver Codeint main(){ vector<int> arr = { 1, 2, 3, 4, 5, 3, 2 }; int K = 1; cout << longestSubsequence(arr, K);} |
6
Time Complexity: O(N)
Auxiliary Space: O(N)


