Find the second largest number in { 10, 5, 20, 8, 20 } (answer: 10).
Ready — edit the code above and click Run.
using System;
class Program
{
static void Main()
{
int[] arr = { 10, 5, 20, 8, 20 };
int first = int.MinValue, second = int.MinValue;
foreach (var x in arr)
{
if (x > first) { second = first; first = x; }
else if (x > second && x < first) second = x;
}
Console.WriteLine(second);
}
}
Try solving on your own first, then reveal the official answer.
Track two variables in one pass—handles duplicates correctly when second must be strictly less than max.