Hey, please explain me where and why my logic is wrong.
If complete logic is wrong then please explain the correct logic for this problem.
#include<iostream>
#include<algorithm>
#define ll long long int
using namespace std;
ll max_sum(int a[], int b[], int n){
sort(a,a+n);
// copy largest n/2 elements in array b
for(int i=n/2,j=0; i<n; i++,j++){
b[j] = a[i];
}
// Greedy step -> maximize (b[i]-a[i])
// difference of array
ll sum = 0;
for(int i=0; i<n/2; i++){
sum += abs(b[i]-a[i]);
}
return sum;
}
ll min_sum(int a[], int b[], int n){
// Greedy step -> minimize (b[i]-a[j])
ll sum = 0;
for(int i=0; i<n; i+=2){
sum += abs(a[i+1]-a[i]);
}
return sum;
}
int main(){
int t;
cin>>t;
while(t--){
int n; // always even
cin>>n;
int a[100005];
int b[100005];
for(int i=0; i<n; i++){
cin>>a[i];
}
cout<<min_sum(a,b,n)<<" "<<max_sum(a,b,n)<<endl;
}
return 0;
}