Problem 11
Second Largest Distinct Element
Easy · 10 pts · Array
Problem
You are given an array of N integers. Find the second-largest distinct value: the largest value that is strictly smaller than the maximum. Repeated copies of the maximum do not count as the second largest. For example, in [5, 5, 3] the answer is 3, not 5. If all elements are equal (or there is only one element), no second-largest distinct value exists, so print -1. You can do this in one pass by tracking the largest and the second-largest distinct values seen so far.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the second-largest distinct element, or -1 if none exists.
Constraints
1 <= N <= 100000; -1000000000 <= array[i] <= 1000000000
Example input
5 12 35 1 10 34
Example output
34
Explanation
In 12 35 1 10 34, the largest value is 35. The largest value strictly smaller than 35 is 34, so the answer is 34.