PROBLEM LINK:
DIFFICULTY:
EASY
PREREQUISITES:
Math, Observation.
PROBLEM:
Team Contest
We have n friends with an individual rating stored inside an array.
Our basic task is to find the total rating change, after making the rating of all friends equal to a particular friend say, TEAM LEADER. Choose TEAM LEADER in such a way that the total change is minimum.
EXPLANATION:
To make the total change minimum, it is ideal to choose the median of the array after sorting.
For Sample Input:
2 3 1 5 2
After sorting the array becomes,
1 2 2 3 5
The median of the given sorted array is 2. So, the total rating change corresponding to TEAM LEADER 2 is,
(2-1)+(2-2)+(2-2)+(3-2)+(5-2) = 5
Hence, the output for the given test case is 5.
SOLUTIONS:
Solution
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll n;
cin>>n;
vector<ll> v(n);
for(ll i=0;i<n;i++)
cin>>v[i];
sort(v.begin(),v.end());
ll x=v[n/2];
ll ans=0;
for(ll i=0;i<n;i++)
{
ans+=abs(v[i]-x);
}
cout<<ans;
}