Open In App

Longest subsequence such that difference between adjacent elements is K

Improve
Improve
Like Article
Like
Save
Share
Report

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:

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 K
int 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 Code
int main()
{
    vector<int> arr = { 1, 2, 3, 4, 5, 3, 2 };
    int K = 1;
 
    cout << longestSubsequence(arr, K);
}


Java




// Java code for the above approach
import java.util.HashMap;
 
class GFG {
 
    // Function to find the longest
    // subsequence such that difference
    // between adjacent elements is K
    public static int longestSubsequence(int[] arr, int K) {
 
        // Stores length of longest
        // subsequence in a map
        HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
 
        // Variable to store the maximum
        // length of subsequence
        int mx = 1;
 
        // Loop to iterate through the
        // given array
        for (int x : arr) {
            mp.put(x, 1);
 
            // If (x - K) exists
            if (mp.containsKey(x - K)) {
                mp.put(x, 1 + mp.get(x - K));
            }
 
            // If (x + K) exists
            if (mp.containsKey(x + K)) {
                mp.put(x, Math.max(mp.get(x), 1 + mp.get(x + K)));
            }
            mx = Math.max(mx, mp.get(x));
        }
 
        // Return Answer
        return mx;
    }
 
    // Driver Code
    public static void main(String args[]) {
        int[] arr = { 1, 2, 3, 4, 5, 3, 2 };
        int K = 1;
 
        System.out.print(longestSubsequence(arr, K));
    }
}
 
// This code is contributed by gfgking


Python3




# python code for the above approach
 
# Function to find the longest
# subsequence such that difference
# between adjacent elements is K
def longestSubsequence(arr, K):
 
    # Stores length of longest
    # subsequence in a map
    mp = {}
 
    # Variable to store the maximum
    # length of subsequence
    mx = 1
 
    # Loop to iterate through the
    # given array
    for x in arr:
        mp[x] = 1
 
        # If (x - K) exists
        if ((x - K) in mp):
            mp[x] = 1 + mp[x - K]
 
        # if (x + K) exists
        if ((x+K) in mp):
            mp[x] = max(mp[x], 1 + mp[x + K])
 
        mx = max(mx, mp[x])
 
    # Return Answer
    return mx
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 2, 3, 4, 5, 3, 2]
    K = 1
 
    print(longestSubsequence(arr, K))
 
# This code is contributed by rakeshsahni


C#




// C# code for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find the longest
// subsequence such that difference
// between adjacent elements is K
static int longestSubsequence(List<int> arr, int K)
{
     
    // Stores length of longest
    // subsequence in a map
    Dictionary<int,
               int> mp = new Dictionary<int,
                                        int>();
 
    // Variable to store the maximum
    // length of subsequence
    int mx = 1;
 
    // Loop to iterate through the
    // given array
    foreach(int x in arr)
    {
        mp[x] = 1;
 
        // If (x - K) exists
        if (mp.ContainsKey(x - K))
        {
            mp[x] = 1 + mp[x - K];
        }
 
        // If (x + K) exists
        if (mp.ContainsKey(x + K))
        {
            mp[x] = Math.Max(mp[x], 1 + mp[x + K]);
        }
        mx = Math.Max(mx, mp[x]);
    }
 
    // Return Answer
    return mx;
}
 
// Driver Code
public static void Main()
{
    List<int> arr = new List<int>(){ 1, 2, 3, 4, 5, 3, 2 };
    int K = 1;
 
    Console.Write(longestSubsequence(arr, K));
}
}
 
// This code is contributed by ukasp


Javascript




  <script>
      // JavaScript code for the above approach
 
      // Function to find the longest
      // subsequence such that difference
      // between adjacent elements is K
      function longestSubsequence(arr, K)
      {
       
          // Stores length of longest
          // subsequence in a map
          let mp = new Map();
 
          // Variable to store the maximum
          // length of subsequence
          let mx = 1;
 
          // Loop to iterate through the
          // given array
          for (let x of arr) {
              mp.set(x, 1)
 
              // If (x - K) exists
              if (mp.has(x - K)) {
                  mp.set(x, 1 + mp.get(x - K));
              }
 
              // if (x + K) exists
              if (mp.has(x + K)) {
                  mp.set(x, 1 + mp.get(x + K));
              }
 
              mx = Math.max(mx, mp.get(x));
          }
 
          // Return Answer
          return mx;
      }
 
      // Driver Code
      let arr = [1, 2, 3, 4, 5, 3, 2];
      let K = 1;
 
      document.write(longestSubsequence(arr, K));
 
// This code is contributed by Potta Lokesh
  </script>


Output

6

Time Complexity: O(N)
Auxiliary Space: O(N)

 



Last Updated : 20 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads