Open In App

Longest Subsequence with absolute difference of pairs as at least Subsequence’s maximum

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of length N. The task is to find the length of the longest subsequence of the array such that the absolute difference between any pair of elements is greater than or equal to the maximum element in that subsequence.

Examples:

Input: N = 6, arr[] = {1, 1, 0, 0, 0, 0}
Output: 4
Explanation: Considering 0 as max element of subsequence, longest array can be made 
by choosing elements from arr3 to arr6 => {0, 0, 0, 0}. 
Thus, Length of above subsequence = 4.

Input: N = 4, arr[] = {-3, 0, 2, 0}
Output: 3

 

Approach: The solution to the problem is based on the following observation.

  •  Try to include as many negative and 0 value elements as possible because in an array of all negative and zero value elements the absolute difference of any two pairs would always be greater than or equal to zero and the maximum element in that subsequence would be less than or equal to zero.
  • Now, the focus should be to add only one positive element if possible, in the subsequence because on considering a number of positive elements greater than or equal to 2, a scenario might come when both positive elements would be in consideration as a pair then their absolute difference would be less than the maximum element(which would be one of the taken positive element).

The above observation can be implemented by sorting the array and finding the longest sequence that satisfies the given condition of the problem statement. Follow the below steps:

  • Sort Array in Descending order.
  • Initialize the answer variable with a value equal to given N.
  • Start Iterating the array, and take the count of how many elements cannot be taken into consideration for a subsequence by checking if the difference between any pair is greater than or equal to the maximum element of that subsequence.
  • Return (answer – element count).

Below is the implementation of the above approach

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to get longest subsequence
int solve(int arr[], int n)
{
 
    // Sort the array in descending order
    sort(arr, arr + n, greater<int>());
 
    // Initialize answer variable equal
    // to value of N
    int answer = n;
 
    // Count of elements
    // that wont be included in
    // the longest subsequence
    int j = 0;
 
    // Traversing the array
    for (int i = 0; i < n; i++) {
 
        if (i + 1 < n) {
 
            // Checking using the given condition
            // and taking count of elements
            // not to be included in the answer
            if (abs(arr[i] - arr[i + 1])
                < arr[j]) {
                j++;
            }
        }
    }
 
    // Printing the final answer
    return answer - j;
}
 
// Driver Code
int main()
{
    int N = 4;
    int arr[] = { -3, 0, 2, 0 };
 
    // Function call
    int ans = solve(arr, N);
    cout << ans;
    return 0;
}


Java




// Java code for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to reverse the array
  static void reverse(int a[], int n){
    int i, k, t;
    for (i = 0; i < n / 2; i++) {
      t = a[i];
      a[i] = a[n - i - 1];
      a[n - i - 1] = t;
    }
  }
 
  // Function to get longest subsequence
  static int solve(int arr[], int n)
  {
 
    // Sort the array in descending order
    Arrays.sort(arr);
    //Now reverse the array
    reverse(arr, n);
 
    // Initialize answer variable equal
    // to value of N
    int answer = n;
 
    // Count of elements
    // that wont be included in
    // the longest subsequence
    int j = 0;
 
    // Traversing the array
    for (int i = 0; i < n; i++) {
 
      if (i + 1 < n) {
 
        // Checking using the given condition
        // and taking count of elements
        // not to be included in the answer
        if (Math.abs(arr[i] - arr[i + 1])
            < arr[j]) {
          j++;
        }
      }
    }
 
    // Printing the final answer
    return answer - j;
  }
 
  // Driver Code
  public static void main (String[] args) {
    int N = 4;
    int arr[] = { -3, 0, 2, 0 };
 
    // Function call
    int ans = solve(arr, N);
    System.out.println(ans);
 
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3




# Python 3 code for the above approach
 
# Function to get longest subsequence
def solve(arr, n):
 
    # Sort the array in descending order
    arr.sort()
    arr.reverse()
 
    # Initialize answer variable equal
    # to value of N
    answer = n
 
    # Count of elements
    # that wont be included in
    # the longest subsequence
    j = 0
 
    # Traversing the array
    for i in range(n):
 
        if (i + 1 < n):
 
            # Checking using the given condition
            # and taking count of elements
            # not to be included in the answer
            if (abs(arr[i] - arr[i + 1])
                    < arr[j]):
                j += 1
 
    # Printing the final answer
    return answer - j
 
# Driver Code
if __name__ == "__main__":
 
    N = 4
    arr = [-3, 0, 2, 0]
 
    # Function call
    ans = solve(arr, N)
    print(ans)
 
    # This code is contributed by ukasp.


C#




// C# code for the above approach
using System;
class GFG {
 
  // Function to reverse the array
  static void reverse(int[] a, int n)
  {
    int i, k, t;
    for (i = 0; i < n / 2; i++) {
      t = a[i];
      a[i] = a[n - i - 1];
      a[n - i - 1] = t;
    }
  }
 
  // Function to get longest subsequence
  static int solve(int[] arr, int n)
  {
 
    // Sort the array in descending order
    Array.Sort(arr);
 
    // Now reverse the array
    reverse(arr, n);
 
    // Initialize answer variable equal
    // to value of N
    int answer = n;
 
    // Count of elements
    // that wont be included in
    // the longest subsequence
    int j = 0;
 
    // Traversing the array
    for (int i = 0; i < n; i++) {
 
      if (i + 1 < n) {
 
        // Checking using the given condition
        // and taking count of elements
        // not to be included in the answer
        if (Math.Abs(arr[i] - arr[i + 1])
            < arr[j]) {
          j++;
        }
      }
    }
 
    // Printing the final answer
    return answer - j;
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 4;
    int[] arr = { -3, 0, 2, 0 };
 
    // Function call
    int ans = solve(arr, N);
    Console.WriteLine(ans);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to get longest subsequence
       function solve(arr, n) {
 
           // Sort the array in descending order
           arr.sort(function (a, b) { return b - a })
 
           // Initialize answer variable equal
           // to value of N
           let answer = n;
 
           // Count of elements
           // that wont be included in
           // the longest subsequence
           let j = 0;
 
           // Traversing the array
           for (let i = 0; i < n; i++) {
 
               if (i + 1 < n) {
 
                   // Checking using the given condition
                   // and taking count of elements
                   // not to be included in the answer
                   if (Math.abs(arr[i] - arr[i + 1])
                       < arr[j]) {
                       j++;
                   }
               }
           }
 
           // Printing the final answer
           return answer - j;
       }
 
       // Driver Code
 
       let N = 4;
       let arr = [-3, 0, 2, 0];
 
       // Function call
       let ans = solve(arr, N);
       document.write(ans);
 
 
    // This code is contributed by Potta Lokesh
   </script>


 
 

Output

3

 

Time Complexity: O(N*logN) the inbuilt sort function takes N log N time to complete all the operation hence time taken by the algorithm is N log N
Auxiliary Space: O(1) since no extra array is used the space taken up by the algorithm is constant

 



Last Updated : 22 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads