Question: You are given an array. The array can contain positive and negative integers. You need to find two elements such that their sum is closest


You are given an array. The array can contain positive and negative integers. You need to find two elements such that their sum is closest to zero.


For example, you are given an array {-4, 7, 6, 2, -5}. The two elements with the sum closest to zero will be -5 and 6.


Input Format:

The input contains the number of elements in the array, followed by the elements in the array.


Output Format:

The output contains the two elements with the sum closest to zero.


Sample Test Cases:

Input 1:

5 -4 7 6 2 -5

Output:

-5 6


Input 2:

8 -50 34 -19 24 33 10 -46 -38

Output:

-38 34


import java.util.Scanner;     class Source  {       static void sumClosestToZero(int arr[], int n)       {                 //Write code here to complete.            }                public static void main (String[] args)        {          int n;          Scanner s = new Scanner(System.in);          n = s.nextInt();          int arr[] = new int[n];          for(int i = 0; i < n; i++)              arr[i] = s.nextInt();                        sumClosestToZero(arr, n);       }  }

Step by Step Solution

3.44 Rating (147 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

import javautilArrays import javautilScanner class Source ... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Operating System Questions!