Given an array of integers, find the sum of any three elements which is closest to zero. The array may contain positive and negative elements.
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import java.util.Arrays; public class JavaExample { public static int findSumClosestToZero(int [] input){ int minSumPositive = Integer.MAX_VALUE; int minSumNegative = Integer.MIN_VALUE; if(input.length<3) { System.out.println("Invalid input"); return minSumPositive; } System.out.println("Given Input: " + Arrays.toString(input)); //sort the array in ascending order Arrays.sort(input); for (int i = 0; i <input.length ; i++) { int a = input[i]; int j = i+1; int k = input.length-1; while(j<k){ int sum = a + input[j] + input[k]; if(sum==0) return 0; else if(sum>0){ minSumPositive = Math.min(sum, minSumPositive); k--; }else{ minSumNegative = Math.max(sum, minSumNegative); j++; } } } if(Math.abs(minSumNegative)<minSumPositive) return minSumNegative; return minSumPositive; } public static void main(String[] args) { int [] input = {-1, 4, -2, 5, 10, -5}; System.out.println("Minimum Sum with three elements is: " + findSumClosestToZero(input)); } } |
Output:
1 2 3 4 | Given Input: [-1, 4, -2, 5, 10, -5] Minimum Sum with three elements is: 1 |