#K76122. Second Largest Element Finder

    ID: 34573 Type: Default 1000ms 256MiB

Second Largest Element Finder

Second Largest Element Finder

You are given an integer array. Your task is to find the second largest element in the array. If the second largest element does not exist (for example, when all elements are identical or there is only one element), you should output -1.

The solution must read input from stdin and output the result to stdout.

Note: The approach should aim for an optimal solution in one pass over the array.

Example 1:

Input:
5
10 5 8 12 3

Output: 10

</p>

Example 2:

Input:
4
4 4 4 4

Output: -1

</p>

Example 3:

Input:
6
7 -2 3 19 19 7

Output: 7

</p>

The underlying logic can be formulated as:

if n<2 then return 1,\text{{if }} n < 2 \text{{ then return }} -1, $$\text{{initialize }} first = -\infty \text{{ and }} second = -\infty, $$for each element x in array:\text{{for each element }} x \text{{ in array:}} $$\quad \text{{if }} x > first \text{{ then }} second = first,\; first = x, $$$$\quad \text{{else if }} first > x > second \text{{ then }} second = x. $$

Finally, output second if a valid value exists; otherwise, output -1.

inputFormat

The first line contains a single integer n representing the number of elements in the array.

The second line contains n space-separated integers representing the elements of the array.

outputFormat

Output a single integer: the second largest element in the array, or -1 if it does not exist.

## sample
5
10 5 8 12 3
10