How to find the sum of two elements in a table closest to zero

advertisements

How to find two elements from an array whose sum is closest to zero but not zero(note: -1 is closest to zero than +2).I tried this...

 int a[]=new int[n];
 int b[]=new int[2];
 int prev=0;
 for(int i=0;i<n;a[i++]=in.nextInt());
 for(int i=0;i<a.length;i++){
     for(int j=i+1;j<a.length;j++){
         int sum=a[i]+a[j];
         if(prev==0)
             prev=sum;
         if(sum > 0){
             if(sum < prev ){
                 prev=sum;
                 b[0]=a[i];
                 b[1]=a[j];
             }
         }
         else if(sum < 0){
             if(-sum < prev){
                 prev=sum;
                 b[0]=a[i];
                 b[1]=a[j];
             }
         }
     }
 }

    Sop(b[0]+" "+b[1]);


I have a few remarks, you are using 3 for loops, which can be improved to just 2 nested for loops (the outer loop for selecting the current element and the inner loop to compare with the other elements).

Also you have multiple if tests to check if the sum is now closer to zero then the previous sum. However these if tests can be reduced to just one if test, by taking the absolute value of the sum instead of testing on sum > 0 and sum < 0, which is fine for the readability.

This is what i came up with :

int array[] = new int[5];
array[0] = -3; array[1] = -2; array[2] = -1; array[3] = 1; array[4] = 2; // Fill array

int idx[] = new int[2]; // Will store the result (index of the two elements that need to be added)
double lowest_sum = Double.POSITIVE_INFINITY; // Of type double to be able to use infinity

for(int i = 0; i < array.length; i++) {
    // Outer loop --> Uses a current (array[i]) from left to right
    int current = array[i];
    for(int j = i+1; j < array.length; j++) {
        // Inner loop --> Check all elements we didn't used as current till now
        int compare_with = array[j];
        if((Math.abs(current + compare_with) < lowest_sum) && ((current + compare_with) != 0)) {
            // We found two elements whose sum is closer to zero
            lowest_sum = Math.abs(current + compare_with);
            idx[0] = i; // Index of the first element to add
            idx[1] = j; // Index of second element to add
        }
    }
}

int res_idx1 = idx[0];
int res_idx2 = idx[1];
System.out.println("The first element to add is : " + array[res_idx1] + "\nThe second element to add is : " + array[res_idx2]);

Input : array = [-3, -2, -1, 1, 2] , Output : The first element to add is : -3, The second element to add is : 2

Note that this code will print a solution and not all solutions (if multiple solutions exists). It should be fairly trivial to edit the code such that it returns all solutions.