Friday 21 October 2016

Find a Pair Whose Sum is Closest to Zero in Array

This problem is also called minimum absolute sum pair.

You are given an array of integers, containing both +ve and -ve numbers. You need to find the two elements such that their sum is closest to zero.
import java.util.Arrays;

/**
 * Class to find the pair whose sum closer to zero.
 * @author rajesh.kumar
 */
public class SumClosestToZero {

     public static void main(String[] args) {
           int[] array = {10,12,14,16,-8,10,18,19,7,-6};

           getPairWithCloserToZeroSum(array);

     }

     /**
      * Method to print the pair.
      * @param array
      */
     private static void getPairWithCloserToZeroSum(int[] array) {
           Arrays.sort(array);
           int length = array.length;
          
           if(length==0 || length==1) {
                System.out.println("No pair exists !!");
           }
          
           int i = 0;
           int j = length -1;
           int minSum = array[i] + array[j];
           int minL = i; int minR= j;
           while (i  <  j) {
                int sum = array[i] + array[j] ;
                /* If sum of the elements at index i and j equals 0 */
                if (Math.abs(minSum)>Math.abs(sum)) {
                     minSum = sum;
                     minL = i;
                     minR = j;
                } else if(sum<0) {
                     i++;
                 } else {
                     j--;
                }
           }
           System.out.println("Pair is"
               +array[minL]+","+array[minR]+")");
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...