Skills101
← All coding problems

Second Largest Distinct Element

easyPlacement Coding+10 XPTime limit 2s

Find the second largest distinct value in the array: the largest value that is strictly smaller than the maximum. In [10, 20, 20, 5] the answer is 10.

Input:

  • line 1: n
  • line 2: n integers

Output: the second largest distinct value, or -1 if every element is equal.

Constraints: 1 ≤ n ≤ 10⁵, 1 ≤ values ≤ 10⁹.

Think about it: one pass is enough. Keep first and second. When a new value beats first, the old first becomes second. Be careful with duplicates of the maximum.

Sample input 1

4
10 20 20 5

Sample output 1

10

Sample input 2

3
7 7 7

Sample output 2

-1

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.