Medium csharp

Second largest element

Problem

Find the second largest number in { 10, 5, 20, 8, 20 } (answer: 10).

Hints
  • Update first and second when you see a new maximum.

Your practice code

Ready — edit the code above and click Run.

Solution

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.

Explanation

Track two variables in one pass—handles duplicates correctly when second must be strictly less than max.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details