The second highest number
A leaderboard shows only the top name, but the report also wants the runner-up.
- Run the equal values together: 10, 10, 9 has a second largest of 9.
- Fewer than two distinct values gives -1.
SecondLargest(values: list<int>) → int
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public int SecondLargest(List<int> values) {
}
Worked examples
| Call | Result |
|---|---|
SecondLargest(new List<int> { 3, 1, 2 }) | 2 |
SecondLargest(new List<int> { 10, 10, 9 }) | 9 |
SecondLargest(new List<int> { 4, 1, 4, 2, 3 }) | 3 |
SecondLargest(new List<int> { 5 }) | -1 |
Hint
Walk once keeping the two best so far, and ignore a value equal to the current best.
Reference solution in C#
public int SecondLargest(List<int> values) {
int best = 0, second = 0;
bool found = false, started = false;
foreach (var v in values) {
if (!started) { best = v; started = true; continue; }
if (v > best) {
second = best;
found = true;
best = v;
} else if (v < best) {
if (!found || v > second) { second = v; found = true; }
}
}
return found ? second : -1;
}