# HackerEarth K Friends problem solution

In this HackerEarth K Friends problem solution Monk has N friends. They are invited to his birthday party. Each friend has a satisfying factor which is equal to the number of gifts which they are expecting. Monk wants to satisfy at-least K friends but he is unaware of their satisfying factors. So Monk starts distribution of gifts. As soon as a friend is satisfied he won't take more gifts.

Monk will follow a distribution strategy so as to minimize the number of gifts needed to satisfy atleast K of his friends. Find the minimum number of gifts which Monk should carry with himself in the worst case.

## HackerEarth K Friends problem solution.

`#include<bits/stdc++.h>using namespace std;#define ll long long intll n,k,t;vector<ll>v;int main(){    freopen("inp10.txt","r",stdin);    freopen("out10.txt","w",stdout);    ll i,j,ans=0,cur;    cin>>t;    while(t--)    {        cin>>n;        v.clear();        ans=cur=0;        for(i=1;i<=n;i++)        {            cin>>j;            v.push_back(j);        }        sort(v.begin(),v.end());        cin>>k;        i=0;        while(k--)        {            ans+=((n-i)*(v[i]-cur));            cur=v[i];            i++;        }        cout<<ans<<"\n";    }    return 0;}`

### Second solution

`#include<bits/stdc++.h>#define ll long longusing namespace std;int main(){    int t;    cin>>t;    while(t--)    {        int n,a;        cin>>n;        for(int i=0;i<n;i++)            cin>>a[i];        int k;        cin>>k;        sort(a,a+n);        ll ans=0;        for(int i=0;i<k;i++)        {            ans+=(ll)a[i];        }        for(int i=k;i<n;i++)            ans+=(ll)a[k-1];        cout<<ans<<"\n";    }    return 0;}`