Open In App

Longest Subsequence with difference between max and min at most K

Last Updated : 28 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N and a non-negative integer K, the task is to find the length of the longest subsequence such that the difference between the maximum and the minimum of the subsequence is at most K.

Examples:

Input: arr[] = {1, 3, 5, 4, 2}, N = 5, K = 3
Output: 4
Explanation: If we consider, the sequence {1, 3, 4, 2}. The subsequence maximum element is 4 and minimum element is 1 and their absolute difference is 3. So maximum length among all subsequence is 4.

Input: arr[] = {5, 5, 5, 5, 5}, N = 5, K = 1
Output: 5

Naive Approach: The simplest way is to generate all possible subsequence and find the longest among them having the difference between the maximum and the minimum at most K.

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

Efficient Approach: The problem can be solved efficiently using sorting based on the following idea:

If we sort the array we can get the elements in sorted order. Now the task reduces to finding the longest window such that the difference between the last and first element of the window is at most K. This can be solved using two pointer technique.

Follow the steps mentioned below to implement the idea:

  •  Sort the array arr[] in ascending order.
  •  Initialize, i = 0,  j = 0 to implement the two pointer approach and MaxSize = 0 to store the length of the longest subsequence.
  • Run a loop till j < N:
    • If, (arr[j] - arr[i]) ? K [Because the array is sorted so arr[j] is maximum and arr[i] is minimum], update, the MaxSize  to have the maximum length and increment j by 1.
    • Else increment i by 1.
  • Return MaxSize as the required maximum length.

Below is the implementation of the above approach.

C++
// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum length
int findMaxSize(int* arr, int n, int k)
{
    sort(arr, arr + n);
    int i = 0, j = 0, MaxSize = 0;

    // Loop to implement the two pointer technique
    while (j < n) {
        if ((arr[j] - arr[i]) <= k) {
            MaxSize = max(MaxSize, j - i + 1);
            j++;
        }
        else
            i++;
    }

    // Return the maximum size
    return MaxSize;
}

// Driver Code
int main()
{
    int N, K = 3;
    int arr[] = { 1, 3, 5, 4, 2 };
    N = sizeof(arr) / sizeof(arr[0]);

    // Function call
    cout << findMaxSize(arr, N, K);

    return 0;
}
Java
// Java code to implement the approach

import java.io.*;
import java.util.*;

class GFG {

    // Function to find the maximum length
    static int findMaxSize(int[] arr, int n, int k)
    {
        Arrays.sort(arr);
        int i = 0, j = 0, MaxSize = 0;

        // Loop to implement the two pointer technique
        while (j < n) {
            if ((arr[j] - arr[i]) <= k) {
                MaxSize = Math.max(MaxSize, j - i + 1);
                j++;
            }
            else {
                i++;
            }
        }

        // Return the maximum size
        return MaxSize;
    }

    public static void main(String[] args)
    {
        int N, K = 3;
        int[] arr = { 1, 3, 5, 4, 2 };
        N = arr.length;

        // Function call
        System.out.print(findMaxSize(arr, N, K));
    }
}

// This code is contributed by lokeshmvs21.
Python3
# Python code for the above approach

# Function to find the maximum length
def findMaxSize(arr, n, k):
    arr.sort();
    i = 0
    j = 0
    MaxSize = 0;

    # Loop to implement the two pointer technique
    while (j < n):
        if ((arr[j] - arr[i]) <= k):
            MaxSize = max(MaxSize, j - i + 1);
            j += 1
        else:
            i += 1

    # Return the maximum size
    return MaxSize;

# Driver Code
N = 3
K = 3
arr = [1, 3, 5, 4, 2];
N = len(arr)

# Function call
print(findMaxSize(arr, N, K));

# This code is contributed by Saurabh Jaiswal
C#
// C# code to implement the approach
using System;

public class GFG {
    // Function to find the maximum length
    static int findMaxSize(int[] arr, int n, int k)
    {
        Array.Sort(arr);
        int i = 0, j = 0, MaxSize = 0;

        // Loop to implement the two pointer technique
        while (j < n) {
            if ((arr[j] - arr[i]) <= k) {
                MaxSize = Math.Max(MaxSize, j - i + 1);
                j++;
            }
            else {
                i++;
            }
        }

        // Return the maximum size
        return MaxSize;
    }

    // Driver Code
    static public void Main()
    {
        int N, K = 3;
        int[] arr = { 1, 3, 5, 4, 2 };
        N = arr.Length;

        // Function call
        Console.Write(findMaxSize(arr, N, K));
    }
}

// This code is contributed by Rohit Pradhan
JavaScript
        // JavaScript code for the above approach

        // Function to find the maximum length
        function findMaxSize(arr, n, k) {
            arr.sort(function (a, b) { return a - b });
            let i = 0, j = 0, MaxSize = 0;

            // Loop to implement the two pointer technique
            while (j < n) {
                if ((arr[j] - arr[i]) <= k) {
                    MaxSize = Math.max(MaxSize, j - i + 1);
                    j++;
                }
                else
                    i++;
            }

            // Return the maximum size
            return MaxSize;
        }

        // Driver Code
        let N, K = 3;
        let arr = [1, 3, 5, 4, 2];
        N = arr.length;

        // Function call
      console.log(findMaxSize(arr, N, K));

 // This code is contributed by Potta Lokesh

Output
4

Time Complexity: O(N * log N)
Auxiliary Space: O(1)


Next Article

Similar Reads