Fredo and Sums

Fredo has an array A consisting of N elements. He wants to divide the array into 

N/2 pairs where each array element comes in exactly one pair. Say that pair i has elements Xi and Yi, he defines S as :

S=i=1N/2abs(XiYi)

He asks you to find the minimum and maximum value of S.

Example:

Input:  n = 4, a ={10,20,-10,0}
Output: 20 40

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void fredoSums(long long nlong long a[])
{
    sort(aa + n);
    long long i = 0j = n - 1;
    long long sum = 0sum1 = 0;
    while (i < j)
    {
        sum += abs(a[i] - a[j]);
        i++;
        j--;
    }
    for (long long i = 0i < ni += 2)
        sum1 += abs(a[i] - a[i + 1]);
    if (sum < sum1)
        cout << sum << " " << sum1 << "\n";
    else
        cout << sum1 << " " << sum << "\n";
}
int main()
{

    long long n = 4;

    long long a[n] = {1020, -100};

    fredoSums(na);

    return 0;
}


No comments:

Post a Comment