Two elements whose sum is closest to zero

An array of integers is given, both positive and negative. You need to find two elements such that their sum is closest to zero.

For the below array, program should print -80 and 85.

1, 60, -10, 70, -80, 85

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication2

{

    class Program

    {

        static void Main(string[] args)

        {

            //Two numbers whose sum is closest to 0

            int[] numArray = { 1, 60, -10, 70, -80, 85 };

            int sum = 0;

            int num1 = 0, num2 = 0;

            if (numArray.Length > 1)

            {

                for (int i = 0; i < numArray.Length – 1; i++)

                {

                    for (int j = i + 1; j < numArray.Length; j++)

                    {

                        if (i == 0 && j == 1)

                        {

                            sum = numArray[i] + numArray[j];

                            num1 = numArray[i];

                            num2 = numArray[j];

                        }

                        else

                        {

                            if (Math.Abs(sum) > Math.Abs(numArray[i] + numArray[j]))

                            {

                                sum = numArray[i] + numArray[j];

                                num1 = numArray[i];

                                num2 = numArray[j];

                            }

                        }

                    }

                }

                Console.WriteLine("Numbers whose sum is closest to 0: {0} {1}", num1, num2);

            }

        }

    }

}

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s