Longest subsequence having difference between the maximum and minimum element equal to K

Given an array arr[] consisting of N integers and an integer K, the task is to find the longest subsequence of the given array such that the difference between the maximum and the minimum element in the subsequence is exactly K.
Examples:
Input: arr[] = {1, 3, 2, 2, 5, 2, 3, 7}, K = 1
Output: 5
Explanation:
The longest subsequence whose difference between the maximum and minimum element is K(= 1) is {3, 2, 2, 2, 3}.
Therefore, the length is 5.Input: arr [] = {4, 3, 3, 4}, K = 4
Output: 0
Naive Approach: The simplest approach is to generate all possible subsequences of the given array and for every subsequence, find the difference between the maximum and minimum values in the subsequence. If it is equal to K, update the resultant longest subsequence length. After checking for all subsequences, print the maximum length obtained.
Time Complexity: O(2N)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is based on the observation that in the required subsequence, only two unique elements can be present, and their difference should be K. The problem can be solved by Hashing, to store the frequency of each array element. Follow the steps below to solve the problem:
- Initialize a variable, say ans, to store the length of the longest subsequence.
- Initialize a hashmap, say M, that stores the frequency of the array elements.
- Traverse the array arr[] using the variable i and for each array element arr[i], increment the frequency of arr[] in M by 1.
- Now traverse the hashmap M and for each key(say X) in M, if (X + K) is also present in the M, then update the value of ans to the maximum of ans and the sum of the value of both the keys.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find longest subsequence// having absolute difference between// maximum and minimum element Kvoid longestSubsequenceLength(int arr[],                              int N, int K){    // Stores the frequency of each    // array element    unordered_map<int, int> um;Â
    // Traverse the array arr[]    for (int i = 0; i < N; i++)Â
        // Increment um[arr[i]] by 1        um[arr[i]]++;Â
    // Store the required answer    int ans = 0;Â
    // Traverse the hashmap    for (auto it : um) {Â
        // Check if it.first + K        // exists in the hashmap        if (um.find(it.first + K)            != um.end()) {Â
            // Update the answer            ans = max(ans,                      it.second                          + um[it.first + K]);        }    }Â
    // Print the result    cout << ans;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 1, 3, 2, 2, 5, 2, 3, 7 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â int K = 1;Â
    longestSubsequenceLength(arr, N, K);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;Â
class GFG{  // Function to find longest subsequence// having absolute difference between// maximum and minimum element Kstatic void longestSubsequenceLength(int []arr,                                     int N, int K){         // Stores the frequency of each    // array element    Map<Integer,         Integer> um = new HashMap<Integer,                                   Integer>();Â
    // Traverse the array arr[]    for(int i = 0; i < N; i++)    {        if (um.containsKey(arr[i]))            um.put(arr[i], um.get(arr[i]) + 1);        else            um.put(arr[i], 1);    }         // Store the required answer    int ans = 0;Â
    // Traverse the hashmap    for(Map.Entry<Integer, Integer> e : um.entrySet())    {                 // Check if it.first + K        // exists in the hashmap        if (um.containsKey(e.getKey() + K))         {                         // Update the answer            ans = Math.max(ans, e.getValue() +                            um.get(e.getKey() + K));        }    }Â
    // Print the result    System.out.println(ans);}Â
// Driver Codepublic static void main(String args[]){Â Â Â Â int []arr = { 1, 3, 2, 2, 5, 2, 3, 7 };Â Â Â Â int N = arr.length;Â Â Â Â int K = 1;Â Â Â Â Â Â Â Â Â longestSubsequenceLength(arr, N, K);}}Â
// This code is contributed by bgangwar59 |
Python3
# Python3 program for the above approachfrom collections import defaultdictÂ
# Function to find longest subsequence# having absolute difference between# maximum and minimum element Kdef longestSubsequenceLength(arr, N, K):Â
    # Stores the frequency of each    # array element    um = defaultdict(int)Â
    # Traverse the array arr[]    for i in range(N):Â
        # Increment um[arr[i]] by 1        um[arr[i]] += 1Â
    # Store the required answer    ans = 0Â
    # Traverse the hashmap    for it in um.keys():Â
        # Check if it.first + K        # exists in the hashmap        if (it + K) in um:Â
            # Update the answer            ans = max(ans,                      um[it]                      + um[it + K])Â
    # Print the result    print(ans)Â
# Driver Codeif __name__ == "__main__":Â
    arr = [1, 3, 2, 2, 5, 2, 3, 7]    N = len(arr)    K = 1Â
    longestSubsequenceLength(arr, N, K)Â
    # This code is contributed by chitranayal. |
C#
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{Â
// Function to find longest subsequence// having absolute difference between// maximum and minimum element Kstatic void longestSubsequenceLength(int[] arr,                              int N, int K){       // Stores the frequency of each    // array element    Dictionary<int, int> um = new Dictionary<int, int>();Â
    // Traverse the array    for(int i = 0; i < N; i++)     {                  // Increase the counter of        // the array element by 1        int count = um.ContainsKey(arr[i]) ? um[arr[i]] : 0;         if (count == 0)        {            um.Add(arr[i], 1);        }        else        {            um[arr[i]] = count + 1;        }    }Â
    // Store the required answer    int ans = 0;Â
    // Traverse the hashmap    foreach(KeyValuePair<int, int> it in um)     {Â
        // Check if it.first + K        // exists in the hashmap        if (um.ContainsKey(it.Key + K))        {Â
            // Update the answer            ans = Math.Max(ans, (it.Value + um[it.Key + K]));        }    }Â
    // Print the result    Console.Write(ans);}Â
// Driver Codepublic static void Main(){Â Â Â Â int[] arr = { 1, 3, 2, 2, 5, 2, 3, 7 };Â Â Â Â int N = arr.Length;Â Â Â Â int K = 1;Â
    longestSubsequenceLength(arr, N, K);}}Â
// This code is contributed by splevel62. |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to find longest subsequence// having absolute difference between// maximum and minimum element Kfunction longestSubsequenceLength(arr, N, K){    // Stores the frequency of each    // array element    var um = new Map();Â
    // Traverse the array arr[]    for (var i = 0; i < N; i++)Â
        // Increment um[arr[i]] by 1        if(um.has(arr[i]))        {            um.set(arr[i], um.get(arr[i])+1);        }        else        {            um.set(arr[i], 1);        }Â
    // Store the required answer    var ans = 0;Â
    // Traverse the hashmap    um.forEach((value, key) => {                  // Check if it.first + K        // exists in the hashmap        if (um.has(key+K)) {Â
            // Update the answer            ans = Math.max(ans,                      value                          + um.get(key+K));        }    });Â
    // Print the result    document.write( ans);}Â
// Driver Codevar arr = [ 1, 3, 2, 2, 5, 2, 3, 7 ];var N = arr.length;var K = 1;longestSubsequenceLength(arr, N, K);Â
</script> |
5
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



