Open In App

Minimize operations to empty Array by deleting two unequal elements or one element

Last Updated : 02 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A of size N, the task is to find the minimum number of operations required to make array A empty. The following operations can be performed:

  • Choose any two elements, say X and Y, from A such that X != Y and remove them.
  • Otherwise, choose any one element, say X, from A and remove it.

Examples:

Input: N = 2, A = {2, 2}
Output: 2
Explanation: Remove both values separately and 
it will cost a total of 2 operations.

Input: N = 2, A = {1, 2}
Output: 1
Explanation: Remove both values together in one operation 
and it will cost a total of 1 operation.

Input: N = 6, A = {2, 2, 2, 2, 3, 3}
Output: 4
Explanation: Remove A[0] and A[5] to get A = {2, 2, 2, 3}. 
Remove A[0] and A[3] to get A = {2, 2}. 
Remove A[0] to get A = {2}. 
Remove A[0] to get A = {}.

Approach: The problem can be solved based on the below observation:

It can be observed that if any two elements can be removed simultaneously then it’s best to choose a pair with {Element with maximum frequency, Element with second maximum frequency} at each operation. The last remaining element has to be checked if it can be matched with any non-equal element pairs that are already formed. \

Eventually, If the pairs come to be equal then we have exhausted all pairs with different elements and only equal elements are remaining which can only be removed using separate operations.

Follow the given steps to solve the problem:

  • Traverse array A[] and store all frequencies in a map freq.
  • Push all {frequency, element} pairs into an array of pairs (say arrPos[]).
  • Sort arrPos based on frequencies.
  • Traverse arrPos in reverse order (say i) with j = i – 1.
    • Traverse in a nested order until frequency at arrPos[i] is not 0 and j ? 0.
      • Store all formed pairs in an array pair (say optimalPairs[]).
      • Add minimum of frequency at arrPos[i] and arrPos[j] to OpCnt.
      • Subtract minimum of frequency at arrPos[i] and arrPos[j] from frequency of arrPos[i] and arrPos[j] and decrement j.
  • Traverse arrPos[] again to find the non-zero frequency and break after adding that frequency at arrPos[i] to OpCnt.
  • Traverse pair optimalPairs and decrement OpCnt by 1 and frequency at arrPos[i] by 2 if the remaining element at arrPos[i] is not equal to the pair in optimalPairs.
  • Return OpCnt as the final answer.

Below is the Implementation of this approach:

C++14




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum number of
// operations to empty the array
int minOperationToEmpty(int* A, int& N)
{
    int j, i, OpCnt = 0;
    unordered_map<int, int> freq;
    vector<pair<int, int> > arrPos, optimalPairs;
 
    // Loop to find the frequency
    for (i = 0; i < N; i++)
        freq[A[i]]++;
 
    for (auto& x : freq)
        arrPos.push_back({ x.second, x.first });
 
    // Sort based on frequency
    sort(arrPos.begin(), arrPos.end());
 
    // Find the unequal elements pairs
    for (i = arrPos.size() - 1; i >= 1; i--) {
        j = i - 1;
        while (arrPos[i].first != 0 && j >= 0) {
            int temp
                = min(arrPos[i].first, arrPos[j].first);
            int loop = temp;
            while (loop--)
                optimalPairs.push_back(
                    { arrPos[i].second, arrPos[j].second });
 
            OpCnt += temp;
            arrPos[i].first -= temp;
            arrPos[j--].first -= temp;
        }
    }
 
    // Loop to find equal valued pairs
    for (i = 0; i < arrPos.size(); i++) {
        if (arrPos[i].first) {
            OpCnt += arrPos[i].first;
            break;
        }
    }
    // Loop to assign equal elements with unequal pairs
    for (j = 0; j < optimalPairs.size()
                && arrPos[i].first >= 2;
         j++) {
        if (optimalPairs[j].first != arrPos[i].second
            && optimalPairs[j].second != arrPos[i].second) {
            OpCnt--;
            arrPos[i].first -= 2;
        }
    }
    return OpCnt;
}
 
// Driver code
int main()
{
    int A[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    cout << minOperationToEmpty(A, N);
    return 0;
}


Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
class pair {
    int first, second;
    pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
class GFG {
 
    static class Sorting implements Comparator<pair> {
        public int compare(pair p1, pair p2)
        {
            if (p2.second == p1.second) {
                return p2.first - p1.first;
            }
            return p2.second - p1.second;
        }
    }
 
    // Function to find minimum number of
    // operations to empty the array
    static int minOperationToEmpty(int[] A, int N)
    {
        int j, i, OpCnt = 0;
        HashMap<Integer, Integer> freq = new HashMap<>();
        List<pair> arrPos = new ArrayList<>();
        List<pair> optimalPairs = new ArrayList<>();
 
        // Loop to find the frequency
        for (i = 0; i < N; i++) {
            freq.put(A[i], freq.getOrDefault(A[i], 0) + 1);
        }
 
        for (Map.Entry<Integer, Integer> x :
             freq.entrySet()) {
            arrPos.add(new pair(x.getValue(), x.getKey()));
        }
 
        // Sort based on frequency
        Collections.sort(arrPos, new Sorting());
 
        // Find the unequal elements pairs
        for (i = arrPos.size() - 1; i >= 1; i--) {
            j = i - 1;
            while (arrPos.get(i).first != 0 && j >= 0) {
                int temp = Math.min(arrPos.get(i).first,
                                    arrPos.get(j).first);
                int loop = temp;
                while (loop-- > 0) {
                    optimalPairs.add(
                        new pair(arrPos.get(i).second,
                                 arrPos.get(j).second));
                }
                OpCnt += temp;
                arrPos.get(i).first -= temp;
                arrPos.get(j).first -= temp;
                j--;
            }
        }
 
        // Loop to find equal valued pairs
        for (i = 0; i < arrPos.size(); i++) {
            if (arrPos.get(i).first > 0) {
                OpCnt += arrPos.get(i).first;
                break;
            }
        }
 
        return OpCnt;
    }
 
    public static void main(String[] args)
    {
        int[] A = { 1, 2, 3, 4, 5, 6, 7, 8 };
        int N = A.length;
 
        // Function call
        System.out.print(minOperationToEmpty(A, N));
    }
}
 
// This code is contributed by lokeshmvs21.


Python3




# Function to find minimum number of
# operations to empty the array
def minOperationToEmpty(A, N):
    OpCnt = 0
    freq = {}
    for z in range(0,10):
        freq[z] = 0
    arrPos = []
    optimalPairs = []
 
    # Loop to find the frequency
    for i in range(0,N):
        freq[A[i]] = freq[A[i]]+1
 
    for i in range(0,10):
        if(freq[i]>0):
            arrPos.append([ freq[i], i ])
    # Sort based on frequency
    arrPos.sort()
     
    # Find the unequal elements pairs
    for i in range(len(arrPos)-1,0,-1):
        j = i - 1
        while (arrPos[i][0] != 0 and j >= 0):
            temp = min(arrPos[i][0], arrPos[j][0])
            loop = temp
            while (loop>0):
                optimalPairs.append([ arrPos[i][1], arrPos[j][1] ])
                loop-=1
 
            OpCnt += temp
            arrPos[i][0] -= temp
            arrPos[j][0] -= temp
            j-=1
         
    # Loop to find equal valued pairs
    for i in range(0,len(arrPos)):
        if (arrPos[i][0]>0):
            OpCnt += arrPos[i][0]
            break
         
    # Loop to assign equal elements with unequal pairs
    for j in range(0,len(optimalPairs)):
        if(arrPos[i][0] >= -1):
            break
         
        if (optimalPairs[j][0] != arrPos[i][1] and optimalPairs[j][1] != arrPos[i][1]):
            OpCnt -= 1
            arrPos[i][0] -= 2
 
    return OpCnt
 
# Driver code
A = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
N = len(A)
 
# Function Call
print(minOperationToEmpty(A, N))
 
# This code is contributed by akashish__


C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
class GFG {
    static int Compare(KeyValuePair<int, int> a,
                       KeyValuePair<int, int> b)
    {
        return a.Key.CompareTo(b.Key);
    }
   
    // Function to find minimum number of
    // operations to empty the array
    static int minOperationToEmpty(int[] A, int N)
    {
        int j, i, OpCnt = 0;
        Dictionary<int, int> freq
            = new Dictionary<int, int>();
        var arrPos = new List<KeyValuePair<int, int> >();
        var optimalPairs
            = new List<KeyValuePair<int, int> >();
 
        // Loop to find the frequency
        for (i = 0; i < N; i++) {
            if (freq.ContainsKey(A[i])) {
                var val = freq[A[i]];
                freq.Remove(A[i]);
                freq.Add(A[i], val + 1);
            }
            else
                freq.Add(A[i], 1);
        }
        foreach(var e in freq) arrPos.Add(
            new KeyValuePair<int, int>(e.Value, e.Key));
 
        // Sort based on frequency
        arrPos.Sort(Compare);
 
        // Find the unequal elements pairs
        for (i = arrPos.Count - 1; i >= 1; i--) {
            j = i - 1;
            while (arrPos[i].Key != 0 && j >= 0) {
                int temp = Math.Min(arrPos[i].Key,
                                    arrPos[j].Key);
                int loop = temp;
                while (loop-- != 0)
                    optimalPairs.Add(
                        new KeyValuePair<int, int>(
                            arrPos[i].Value,
                            arrPos[j].Value));
 
                OpCnt += temp;
                var p = new KeyValuePair<int, int>(
                    arrPos[i].Key - temp, arrPos[i].Value);
                arrPos[i] = p;
                p = new KeyValuePair<int, int>(
                    arrPos[j].Key - temp, arrPos[j].Value);
                arrPos[j] = p;
                j--;
            }
        }
 
        // Loop to find equal valued pairs
        for (i = 0; i < arrPos.Count; i++) {
            if (arrPos[i].Key != 0) {
                OpCnt += arrPos[i].Key;
                break;
            }
        }
 
        // Loop to assign equal elements with unequal pairs
        for (j = 0;
             j < optimalPairs.Count && i < arrPos.Count
             && arrPos[i].Key >= 2;
             j++) {
            if (optimalPairs[j].Key != arrPos[i].Value
                && optimalPairs[j].Value
                       != arrPos[i].Value) {
                OpCnt--;
                Console.WriteLine(i);
                var p = new KeyValuePair<int, int>(
                    arrPos[i].Key - 2, arrPos[i].Value);
                arrPos[i] = p;
            }
        }
        return OpCnt;
    }
    static void Main()
    {
 
        int[] A = { 1, 2, 3, 4, 5, 6, 7, 8 };
        int N = A.Length;
 
        // Function Call
        Console.Write(minOperationToEmpty(A, N));
    }
}
 
// This code is contributed by garg28harsh.


Javascript




// JS code to implement the approach
 
// Function to find minimum number of
// operations to empty the array
function minOperationToEmpty(A, N) {
    let j, i, OpCnt = 0;
    let freq = new Map();
    let arrPos = [];
    let optimalPairs = [];
 
    // Loop to find the frequency
    for (i = 0; i < N; i++)
        freq.set(A[i], 1);
 
 
    for (let [key, value] of freq) {
        arrPos.push({
            "first": value,
            "second": key
        });
    }
 
    // Sort based on frequency
    arrPos.sort();
 
    // Find the unequal elements pairs
    for (i = arrPos.length - 1; i >= 1; i--) {
        j = i - 1;
        while (arrPos[i].first != 0 && j >= 0) {
            let temp
                = Math.min(arrPos[i].first, arrPos[j].first);
            let loop = temp;
            while (loop--)
                optimalPairs.push(
                    {
                        "first": arrPos[i].second,
                        "second": arrPos[j].second
                    });
 
            OpCnt += temp;
            arrPos[i].first -= temp;
            arrPos[j--].first -= temp;
        }
    }
 
    // Loop to find equal valued pairs
    for (i = 0; i < arrPos.length; i++) {
        if (arrPos[i].first) {
            OpCnt += arrPos[i].first;
            break;
        }
    }
    i = i - 1;
    // Loop to assign equal elements with unequal pairs
    for (j = 0; j < optimalPairs.length
        && arrPos[i].first >= 2;
        j++) {
        if (optimalPairs[j].first != arrPos[i].second
            && optimalPairs[j].second != arrPos[i].second) {
            OpCnt--;
            arrPos[i].first -= 2;
        }
    }
    return OpCnt;
}
 
// Driver code
let A = [1, 2, 3, 4, 5, 6, 7, 8];
let N = A.length;
 
// Function Call
console.log(minOperationToEmpty(A, N));
 
// This code is contributed by akashish__


Output

4

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads