Our task is to find top two integers from an integer array. For example:

Array: []

Output: Invalid Input

Array: [-1]

output: Max1: -1, Max2: -1

Array: [2,18]

Output: Max1: 2, Max2: 18

Array:[15, 45, 34, 100, -456, 432, 2, 1000]

Output: Max1: 1000, Max2: 432

Code in C#:

 class FindTopTwoIetemsFromUnSortedArray
    {
        static void Main(string[] args)
        {
            int[] arr = { 12342,-162361,12342};
            FindTopTwoMaxIntegers(arr);
            Console.ReadKey();
        }

        static void FindTopTwoMaxIntegers(int[] arr)
        {
            if (arr == null || arr.Length == 0)
            {
                Console.WriteLine("Invalid input");
            }
            else
            {
                int max1 = int.MinValue, max2 = int.MinValue;
                foreach (int item in arr)
                {
                    if (item >= max1)
                    {
                        max2 = max1;
                        max1 = item;
                    }
                    else if (item <item > max2)
                    {
                        max2 = item;
                    }
                }

                if (max2 == int.MinValue)
                {
                    max2 = max1;
                }

                Console.WriteLine($"Max1:{max1}, Max2: {max2}");
            }
        }
    }
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