In this HackerEarth Add - Subtract problem solution Chandan is back with his array to blow your mind. As usual Chandan has an array consisting of N integers .He allows you to perform 2 kinds of operation on his array.
  1. Type 1 : Increment any integer of the array by 1.
  2. Type 2 : Decrement any integer of the array by 1.
You can perform these operation as many times as you want on his array.

Each operation of Type 1 costs 3 while each operation of Type 2 costs 5.

Now Chandan wants to have K equal elements in his array.So he asks you to tell him the minimum cost required in obtaining K equal elements in his array.


HackerEarth Add - Subtract problem solution


HackerEarth Add - Subtract problem solution.

#include <bits/stdc++.h>
#define _ ios_base::sync_with_stdio(false);cin.tie(0);
using namespace std;
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define mp make_pair
#define all(a) a.begin(),a.end()
#define bitcnt(x) __builtin_popcountll(x)
#define MOD 1000000000
#define MAXN 500005
typedef unsigned long long int uint64;
typedef long long int int64;

int a[101];

int main(){
int t,n,i,k,j,cost;
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&k);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
int ans=1e9;
for(i=1;i<=100;i++){
vector<int>v;
for(j=0;j<n;j++){
if(i>=a[j]){
cost=(i-a[j])*3;
}
else{
cost=(a[j]-i)*5;
}
v.pb(cost);
}
sort(all(v));
cost=0;
for(j=0;j<k;j++){
cost+=v[j];
}
ans=min(ans,cost);
}
printf("%d\n",ans);
}
fclose(stdout);
return 0;
}

Second solution

#include<bits/stdc++.h>
#define assn(n,a,b) assert(n<=b && n>=a)
using namespace std;
#define pb push_back
#define mp make_pair
#define clr(x) x.clear()
#define sz(x) ((int)(x).size())
#define F first
#define S second
#define REP(i,a,b) for(i=a;i<b;i++)
#define rep(i,b) for(i=0;i<b;i++)
#define rep1(i,b) for(i=1;i<=b;i++)
#define pdn(n) printf("%d\n",n)
#define sl(n) scanf("%lld",&n)
#define sd(n) scanf("%d",&n)
#define pn printf("\n")
typedef pair<int,int> PII;
typedef vector<PII> VPII;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef long long LL;
#define MOD 1000000007
LL mpow(LL a, LL n)
{LL ret=1;LL b=a;while(n) {if(n&1)
ret=(ret*b)%MOD;b=(b*b)%MOD;n>>=1;}
return (LL)ret;}
int main()
{
int t;
sd(t);
while(t--){
int n,k,ar[109],ans=INT_MAX;
sd(n),sd(k);
assn(n,1,100);
assert(k>=1 and k<=n);
for(int i=0; i<n; i++)
sd(ar[i]),assn(ar[i],1,100);
for(int val=0; val<=100; val++){
int cost=0;
VI arr(n);
for(int j=0; j<n; j++)
if(ar[j]>val)arr[j]=(ar[j]-val)*5;
else arr[j]=(val-ar[j])*3;
sort(arr.begin(),arr.end());
for(int j=0; j<k; j++)cost+=arr[j];
ans=min(ans,cost);
}
pdn(ans);
}
return 0;
}