ronith
6/6/2018 - 6:34 AM

Two numbers with sum closest to zero

Question: An Array of integers is given, both +ve and -ve. You need to find the two elements such that their sum is closest to zero

Input 3 3 -8 -66 -60
6 -21 -67 -37 -18 4 -65
2 -24 -73 Output -60 -8 -18 4 -73 -24

#include <iostream>
using namespace std;

int main(){
    int n;
    cin>>n;
    int a[n];
    for(int i=0;i<n;i++)
        cin>>a[i];

    int min_sum= INT_MAX,min_i=0,min_j=1;

    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            if (i !=j){
                int sum = a[i]+a[j];
                if (abs(min_sum) > abs(sum)){
                    min_sum = sum;
                    min_i = i;
                    min_j = j;
                }
            }
        }
    }
    if (a[min_i] < a[min_j])
        cout<< a[min_i]<< "  "<< a[min_j];
    else
        cout<< a[min_j]<< "  "<< a[min_i];
}