Two numbers with sum closest to zero
PROBLEM :
Given an integer array, you need to find the two elements such that their sum is closest to zero.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,the size of array
Each test case consist of a N integers which are the array elements.
Output:
Print the two numbers in ascending order such that their sum is closest to zero.
Constraints:
1 = T = 100
1 = N = 1000
-100007 = a[i] = 100007
Example:
Input
3
3
-8 -66 -60
6
-21 -67 -37 -18 4 -65
2
-24 -73
Output
-60 -8
-18 4
-73 -24
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t ;
cin>>t ;
while(t--)
{
int no ;
cin>>no ;
int arr[no] ;
for(int i=0;i<no;i++)
cin>>arr[i] ;
sort(arr,arr+no) ;
int start,end ;
int near=INT_MAX ;
int i=0,j=no-1 ;
while(i<j)
{
int sum=arr[i]+arr[j] ;
if(sum==0)
{
start=i ;
end=j ;
break ;
}
if(sum<0)
{
if(abs(sum)<abs(near))
{
near=sum ;
start=i ;
end=j ;
}
i++ ;
}
else
{
if(abs(sum)<abs(near))
{
near=sum ;
start=i ;
end=j ;
}
j-- ;
}
}
cout<<arr[start]<<" "<<arr[end]<<endl ;
}
return 0;
}
---------------------------------------------------------------------------------
Given an integer array, you need to find the two elements such that their sum is closest to zero.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,the size of array
Each test case consist of a N integers which are the array elements.
Output:
Print the two numbers in ascending order such that their sum is closest to zero.
Constraints:
1 = T = 100
1 = N = 1000
-100007 = a[i] = 100007
Example:
Input
3
3
-8 -66 -60
6
-21 -67 -37 -18 4 -65
2
-24 -73
Output
-60 -8
-18 4
-73 -24
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t ;
cin>>t ;
while(t--)
{
int no ;
cin>>no ;
int arr[no] ;
for(int i=0;i<no;i++)
cin>>arr[i] ;
sort(arr,arr+no) ;
int start,end ;
int near=INT_MAX ;
int i=0,j=no-1 ;
while(i<j)
{
int sum=arr[i]+arr[j] ;
if(sum==0)
{
start=i ;
end=j ;
break ;
}
if(sum<0)
{
if(abs(sum)<abs(near))
{
near=sum ;
start=i ;
end=j ;
}
i++ ;
}
else
{
if(abs(sum)<abs(near))
{
near=sum ;
start=i ;
end=j ;
}
j-- ;
}
}
cout<<arr[start]<<" "<<arr[end]<<endl ;
}
return 0;
}
---------------------------------------------------------------------------------
Comments
Post a Comment