Tuesday, April 16, 2019

MAXDIFF: Maximum Weight Difference

MAXDIFF: Maximum Weight Difference

Link for the problem: MAXDIFF

SOLUTION:

All the weights can be divided in to two parts, one having 'k' number of weights and another with 'n-k' weights. We have to minimize one part and maximize another. So first we will  sort the sequence, then summing the minimum number of (either k or n-k) elements which will be carried by son.

CODE:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int  n,k;
        cin>>n>>k;
        int a[n],i,s=0,s1=0,s2=0;
        for(i=0;i<n;i++)
        {
            cin>>a[i];
            s+=a[i];
        }
        sort(a,a+n);
        int m=min(k,n-k);
        for(i=0;i<m;i++)
        {
            s1+=a[i];
        }
        printf("%d\n",s-2*s1);
    }
    return 0;

}

No comments:

Post a Comment

CHEFST: Chef and the stones

CHEFST: Chef and the stones Link for the problem:  CHEFST SOLUTION: For a given max possible no of stones that can be removed from ea...