#K76122. Second Largest Element Finder
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</p>Output: 10
Example 2:
Input: 4 4 4 4 4</p>Output: -1
Example 3:
Input: 6 7 -2 3 19 19 7</p>Output: 7
The underlying logic can be formulated as:
$$\text{{initialize }} first = -\infty \text{{ and }} second = -\infty, $$ $$\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.
5
10 5 8 12 3
10