Skip to content
Related Articles

Related Articles

Count of array elements to be removed to make absolute difference between each pair same

Improve Article
Save Article
  • Last Updated : 03 Oct, 2022
Improve Article
Save Article

Given an array arr[] consisting of N integers, the task is to find the minimum number of array elements that must be removed such that the absolute difference between each element pair is equal.

Examples:

Input: arr[] = {1, 2}
Output: 0
Explanation: There is only one pair of integers with absolute difference | arr[1] − arr[2] | = | 1- 2 | = 1. So there is no need to delete any integer from the given array.

Input: arr[] = {2, 5, 1, 2, 2}
Output: 2
Explanation: After deleting 1 and 5, the array A becomes [2, 2, 2] and the absolute difference between each pair of integers is 0.

Approach: The given problem can be solved by counting the frequencies of array elements and print the result based on the following observations:

  • If the maximum frequency among all the array elements is 1, then all (N – 2) elements must be removed.
  • Otherwise, the maximum number of array elements that must be removed is (N – maximum frequency) such that all array elements are the same and the difference between any two pairs of elements is the same.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
void countToMakeDiffEqual(int arr[], int n)
{
    // Stores the element having maximum
    // frequency in the array
    int ma = 0;
 
    unordered_map<int, int> m;
 
    for (int i = 0; i < n; i++) {
         
        m[arr[i]]++;
 
        // Find the most occurring element
        ma = max(ma, m[arr[i]]);
    }
 
    // If only one pair exists then the
    // absolute difference between them
    // will be same
    if (n <= 2)
        cout << 0 << endl;
 
    else if (ma == 1) {
        cout << n - 2 << endl;
    }
 
    // Elements to remove is equal to the
    // total frequency minus frequency
    // of most frequent element
    else
        cout << n - ma << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 5, 1, 2, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    countToMakeDiffEqual(arr, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.HashMap;
 
class GFG {
 
    public static void countToMakeDiffEqual(int arr[], int n)
    {
       
        // Stores the element having maximum
        // frequency in the array
        int ma = 0;
 
        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
 
        for (int i = 0; i < n; i++) {
 
            // m[arr[i]]++;
            if (m.containsKey(arr[i])) {
                m.put(arr[i], m.get(arr[i]) + 1);
            } else {
                m.put(arr[i], 1);
            }
 
            // Find the most occurring element
            ma = Math.max(ma, m.get(arr[i]));
        }
 
        // If only one pair exists then the
        // absolute difference between them
        // will be same
        if (n <= 2)
            System.out.println(0);
 
        else if (ma == 1) {
            System.out.println(n - 2);
        }
 
        // Elements to remove is equal to the
        // total frequency minus frequency
        // of most frequent element
        else
            System.out.println(n - ma);
    }
 
    // Driver Code
    public static void main(String args[]) {
        int arr[] = { 2, 5, 1, 2, 2 };
        int N = arr.length;
 
        countToMakeDiffEqual(arr, N);
    }
}
 
// This code is contributed by gfgking.

Python3




# Python 3 program for the above approach
from collections import defaultdict
 
def countToMakeDiffEqual(arr, n):
 
    # Stores the element having maximum
    # frequency in the array
    ma = 0
 
    m = defaultdict(int)
 
    for i in range(n):
 
        m[arr[i]] += 1
 
        # Find the most occurring element
        ma = max(ma, m[arr[i]])
 
    # If only one pair exists then the
    # absolute difference between them
    # will be same
    if (n <= 2):
        print(0)
 
    elif (ma == 1):
        print(n - 2)
 
    # Elements to remove is equal to the
    # total frequency minus frequency
    # of most frequent element
    else:
        print(n - ma)
 
# Driver Code
if __name__ == "__main__":
 
    arr = [2, 5, 1, 2, 2]
    N = len(arr)
 
    countToMakeDiffEqual(arr, N)
 
    # This code is contributed by ukasp.

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
static void countToMakeDiffEqual(int []arr, int n)
{
    // Stores the element having maximum
    // frequency in the array
    int ma = 0;
 
    Dictionary<int, int> m = new Dictionary<int,int>();
 
    for (int i = 0; i < n; i++) {
        if(m.ContainsKey(arr[i]))
          m[arr[i]]++;
        else
         m.Add(arr[i],1);
 
        // Find the most occurring element
        ma = Math.Max(ma, m[arr[i]]);
    }
 
    // If only one pair exists then the
    // absolute difference between them
    // will be same
    if (n <= 2)
        Console.WriteLine(0);
 
    else if (ma == 1) {
        Console.WriteLine(n - 2);
    }
 
    // Elements to remove is equal to the
    // total frequency minus frequency
    // of most frequent element
    else
        Console.WriteLine(n - ma);
}
 
// Driver Code
public static void Main()
{
    int []arr = { 2, 5, 1, 2, 2 };
    int N = arr.Length;
 
    countToMakeDiffEqual(arr, N);
}
}
 
// This code is contributed by ipg2016107.

Javascript




<script>
      // JavaScript Program to implement
      // the above approach
      function countToMakeDiffEqual(arr, n)
      {
       
          // Stores the element having maximum
          // frequency in the array
          let ma = 0;
 
          let m = new Map();
 
          for (let i = 0; i < n; i++) {
              if (m.has(arr[i])) {
                  m.set(arr[i], m.get(arr[i]) + 1);
              }
              else {
                  m.set(arr[i], 1);
              }
               
              // Find the most occurring element
              ma = Math.max(ma, m.get(arr[i]));
          }
 
          // If only one pair exists then the
          // absolute difference between them
          // will be same
          if (n <= 2) {
              document.write(0 + '<br>');
          }
          else if (ma == 1) {
              document.write(n - 2 + '<br>');
          }
 
          // Elements to remove is equal to the
          // total frequency minus frequency
          // of most frequent element
          else {
              document.write(n - ma + '<br>');
          }
      }
 
      // Driver Code
      let arr = [2, 5, 1, 2, 2];
      let N = arr.length;
 
      countToMakeDiffEqual(arr, N);
 
   // This code is contributed by Potta Lokesh
  </script>

Output: 

2

 

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!