Home Arrays Find two elements in an array such that their sum is closest to 0 (ZERO).

Find two elements in an array such that their sum is closest to 0 (ZERO).

by nikoo28
0 comment 2 minutes read

Question: Given an array with both positive and negative numbers, find the two elements such that their sum is closest to zero. ?

Input: arr [] = {1, 60, -10, 70, -80, 85}
Output: -80, 85 (Their sum is -5 that is closest to 0(zero))

We can solve this problem by a brute force approach. That involves two loops, in the first loop we pick an element from the array and in the second loop we add this element individually with each of the other elements in the array. In the process of doing this we maintain the sum that is closest to zero and store their indexes. At the end of the loop, we just print the elements at the stored indexes.

Here is an implementation of the above algorithm.

//brute force solution to find the two elements
//with sum closest to zero.
int twoElementsWithMinSum(int arr[], int size)
{
	int i,j;
	
	//to store the minimum sum and the indexes
	int min_sum, min_i, min_j;
	
	//validity checking
	if(size<2)
	{
		printf("Invalid input");
		return;
	}
	
	//setting defaults
	min_sum = arr[0] + arr[1];
	min_i = 0;
	min_j = 1;
	
	for(i=0;i<(size-1);i++)
	{
		for(j=i+1;j<size;j++)
		{
			//calculate the sum
			int sum = arr[i] + arr[j];
			
			//we need the absolute value, because we need to know
			//the value that is closest to zero.
			if(abs(min_sum) > abs(sum))
			{
				min_sum =  sum;
				min_i = i;
				min_j = j;
			}
		}
	}
	
	//print the elements
	printf("The elements are:- %d %d",arr[min_i],arr[min_j]);
}

Time Complexity:- O(n2)
Space Complexity:- O(1)

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More