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;
}
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