Longest subsequence having difference between the maximum and minimum element equal to K
Last Updated :
11 May, 2021
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++
#include <bits/stdc++.h>
using namespace std;
void longestSubsequenceLength( int arr[],
int N, int K)
{
unordered_map< int , int > um;
for ( int i = 0; i < N; i++)
um[arr[i]]++;
int ans = 0;
for ( auto it : um) {
if (um.find(it.first + K)
!= um.end()) {
ans = max(ans,
it.second
+ um[it.first + K]);
}
}
cout << ans;
}
int 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
import java.util.*;
class GFG{
static void longestSubsequenceLength( int []arr,
int N, int K)
{
Map<Integer,
Integer> um = new HashMap<Integer,
Integer>();
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 );
}
int ans = 0 ;
for (Map.Entry<Integer, Integer> e : um.entrySet())
{
if (um.containsKey(e.getKey() + K))
{
ans = Math.max(ans, e.getValue() +
um.get(e.getKey() + K));
}
}
System.out.println(ans);
}
public 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);
}
}
|
Python3
from collections import defaultdict
def longestSubsequenceLength(arr, N, K):
um = defaultdict( int )
for i in range (N):
um[arr[i]] + = 1
ans = 0
for it in um.keys():
if (it + K) in um:
ans = max (ans,
um[it]
+ um[it + K])
print (ans)
if __name__ = = "__main__" :
arr = [ 1 , 3 , 2 , 2 , 5 , 2 , 3 , 7 ]
N = len (arr)
K = 1
longestSubsequenceLength(arr, N, K)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void longestSubsequenceLength( int [] arr,
int N, int K)
{
Dictionary< int , int > um = new Dictionary< int , int >();
for ( int i = 0; i < N; i++)
{
int count = um.ContainsKey(arr[i]) ? um[arr[i]] : 0;
if (count == 0)
{
um.Add(arr[i], 1);
}
else
{
um[arr[i]] = count + 1;
}
}
int ans = 0;
foreach (KeyValuePair< int , int > it in um)
{
if (um.ContainsKey(it.Key + K))
{
ans = Math.Max(ans, (it.Value + um[it.Key + K]));
}
}
Console.Write(ans);
}
public static void Main()
{
int [] arr = { 1, 3, 2, 2, 5, 2, 3, 7 };
int N = arr.Length;
int K = 1;
longestSubsequenceLength(arr, N, K);
}
}
|
Javascript
<script>
function longestSubsequenceLength(arr, N, K)
{
var um = new Map();
for ( var i = 0; i < N; i++)
if (um.has(arr[i]))
{
um.set(arr[i], um.get(arr[i])+1);
}
else
{
um.set(arr[i], 1);
}
var ans = 0;
um.forEach((value, key) => {
if (um.has(key+K)) {
ans = Math.max(ans,
value
+ um.get(key+K));
}
});
document.write( ans);
}
var arr = [ 1, 3, 2, 2, 5, 2, 3, 7 ];
var N = arr.length;
var K = 1;
longestSubsequenceLength(arr, N, K);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...