Home

Operations on an Array

You are given an array of containing elements. You need to make the elements of the array equal. You are allowed to do the following operations:
  • Decrease an element by 1. If the element becomes 0, it is removed from the array.
  • Increase an element by 1.

You need to find the minimum number of operations required to do so.

Example:

Input:  n = 3, a = {2, 2, 3}
Output: 1

Approach

C++

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

void operationsOnArray(int nvector<int&a)
{
    long long ans = LLONG_MAX;

    for (int i = 0i < n; ++i)
    {
        long long here = 0;
        for (int j = 0j < n; ++j)
        {
            here += min(abs(a[i] - a[j]), a[j]);
        }
        ans = min(anshere);
    }

    cout << ans << '\n';
}
int main()
{

    int n = 3;

    vector<inta = {223};

    operationsOnArray(na);

    return 0;
}


No comments:

Post a Comment