In this HackerEarth Operations on an Array problem solution, You have given an array A containing N elements. You need to make the elements of the array equal. You are allowed to do the following operations:
  1. Decrease an element by 1. If the element becomes 0, it is removed from the array.
  2. Increase an element by 1.
You need to find the minimum number of operations required to do so.


HackerEarth Operations on an Array problem solution


HackerEarth Operations on an Array problem solution.

#include <bits/stdc++.h>

#define int long long
#define pb push_back
#define pii pair<int,int>
#define vi vector<int>
#define vii vector<pii>
#define mi map<int,int>
#define mii map<pii,int>
#define all(a) (a).begin(),(a).end()
#define x first
#define y second
#define sz(x) (int)x.size()
#define endl '\n'
#define hell 10000000000000007LL
#define rep(i,a,b) for(int i=a;i<b;i++)
using namespace std;
int n,a[1003],ans=hell;
void solve(){
cin>>n;
rep(i,0,n) cin>>a[i];
rep(i,0,n){
int cost=0;
rep(j,0,n){
cost+=min(a[j],abs(a[j]-a[i]));
}
ans=min(ans,cost);
}
cout<<ans<<endl;
}

signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t=1;
// cin>>t;
while(t--){
solve();
}
return 0;
}

Second solution

#include <bits/stdc++.h>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <utility>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <iomanip>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

#define f(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) f(i,0,n)
#define fd(i,a,b) for(i=a;i>=b;i--)
#define pb push_back
#define mp make_pair
#define vi vector< int >
#define vl vector< ll >
#define ss second
#define ff first
#define ll long long
#define pii pair< int,int >
#define pll pair< ll,ll >
#define sz(a) a.size()
#define inf (1000*1000*1000+5)
#define all(a) a.begin(),a.end()
#define tri pair<int,pii>
#define vii vector<pii>
#define vll vector<pll>
#define viii vector<tri>
#define mod (1000*1000*1000+7)
#define pqueue priority_queue< int >
#define pdqueue priority_queue< int,vi ,greater< int > >
#define flush fflush(stdout)
#define primeDEN 727999983
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

// find_by_order() // order_of_key
typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;

#define int ll
int a[1234];

signed main(){
std::ios::sync_with_stdio(false); cin.tie(NULL);
int n;
cin>>n;
int i;
rep(i,n){
cin>>a[i];
}
int sumi=0;
ll iinf=inf;
iinf*=inf;
int mini=iinf;
int j;
rep(i,n){
sumi=0;
rep(j,n){
sumi+=min(a[j],abs(a[i]-a[j]));
}
mini=min(mini,sumi);
}
cout<<mini<<endl;
return 0;
}