Find the largest pair sum in an unsorted array in C#

Given an unsorted array, find the largest pair sum in it. For example, the largest pair sum in {12, 34, 10, 6, 40} is 74. But there is a condition, you can’t traverse array more than once.

class Largest_Pair_Sum_In_Array
{
static void Main(string[] args)
{
int[] arr = { 52, 12, 34, 10, 6, 40, 12, 40, 52 };
int firstMax = 0, secondMax = 0;

for (int i = 0; i < arr.Length; ++i)
{
if (arr[i] > firstMax)
{
secondMax = firstMax;
firstMax = arr[i];
}
else if (arr[i] > secondMax)
{
secondMax = arr[i];
}
}

Console.WriteLine(string.Format(“Largest pair sum in given array is: {0}”, firstMax + secondMax));
Console.ReadKey();
}
}

Advertisements

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