Equal elements

You are given an integer array A consisting of N elements. You can perform the following operations on an array A:

  • Choose any element and increase or decrease it by 3 for 1 coin.
  • Choose any element and increase or decrease it by 2 for free.

You are required to spend the minimum number of coins in order to make all the elements in the array AA equal.

Example:

Input:  n = 4,arr[] = {3, 5, 2, 3};
Output: 1

Approach

Java


public class EqualElements {
    public static void main(String[] args){
        int n = 4;
        int arr[] = { 3523 };
         int cnt[] = new int[2];
         for (int i = 0; i < n; ++i) {
             ++cnt[arr[i] & 1];
         }
        System.out.println(Math.min(cnt[0], cnt[1]));
    }

}

C++

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

int equalElement(int nvector<intarr)
{

    int odd = 0even = 0;
    for (int i = 0i < n; ++i)
    {
        if (arr[i] % 2 == 0)
            even++;
        else
            odd++;
    }
    return min(evenodd);
}
int main()
{

    int n = 4;

    vector<intarr = {3523};

    cout << equalElement(narr<< "\n";

    return 0;
}


No comments:

Post a Comment