Second maximum number

How to find out second maximum number in C#?

Questions by tmounika   answers by tmounika

Showing Answers 1 - 5 of 5 Answers

Werty

  • Nov 10th, 2013
 

For example.

Code
  1. int[] t = new int[5];

  2. int max= 0,max2=0;

  3. Random rnd = new Random();

  4.             for (int i = 0; i < t.Length; i++)

  5.             {

  6.                 t[i] = rnd.Next(10);

  7.             }

  8. for (int i = 0; i < t.Length; i++)

  9.             {

  10.                  Console.WriteLine(t[i]);

  11.             }

  12. for (int i = 0; i < t.Length; i++)

  13.             {

  14.                 if (max < t[i])

  15.                     max = t[i];

  16.             }

  17. for (int i = 0; i < t.Length; i++)

  18.             {

  19.                 if (t[i] != max && t[i] > max2)

  20.                     max2 = t[i];

  21.             }

  22. Console.WriteLine("max2="+max2);

Deepak

  • Mar 11th, 2015
 

Use LINQ

  Was this answer useful?  Yes

Code
  1.  

  2.  var array = new[] { 3, 1, 4, 8 };

  3.             Array.Sort(array);

  4.             if (array.Length - 2 >= 0)

  5.             {

  6.                 var secondMax = array[array.Length - 2];

  7.             }

  8.  

  Was this answer useful?  Yes

This code will work even if array will have a few maximums. Ex: (10, 8, 8, -2, 4, 10, 1)

Code
  1. static int GetSecondMax(int[] array)

  2.         {

  3.             if(array.Length < 2)

  4.                 throw new ArgumentException("array has to have at least 2 elements");

  5.             Array.Sort(array);

  6.             var max = array[array.Length - 1];

  7.             for (var i = 1; i < array.Length; i++)

  8.             {

  9.                 var secondMax = array[array.Length - 1 - i];

  10.                 if (secondMax != max)

  11.                     return secondMax;

  12.             }

  13.             // array has all the same elements. In this case we

  14.             return max;

  15.         }

  Was this answer useful?  Yes

Roger Hyde

  • Feb 6th, 2016
 

Linq makes this quite simple

Code
  1. int GetSecondMax(int[] numbers)

  2. {

  3.         return numbers.Distinct().OrderByDescending(n => n).Skip(1).Take(1).FirstOrDefault();

  4. }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions