#K13861. Find the Second Largest Element

    ID: 24007 Type: Default 1000ms 256MiB

Find the Second Largest Element

Find the Second Largest Element

You are given an array of integers. Your task is to find the second largest distinct element in the array. In other words, if the largest element is \( M \), you must find the largest element in the array that is strictly less than \( M \). If such an element does not exist (for example, when the array is empty or all elements are identical), output -1.

Input Constraints:

  • The first line contains an integer \( n \) which represents the number of elements in the array.
  • The second line contains \( n \) space-separated integers.

Example:

If the input is:

5
10 5 8 3 12

The largest element is 12 and the second largest distinct element is 10, so the output should be 10.

The problem can be summarized by the formula: Let \( A \) be the array, and \( M = \max(A) \). Find \( S = \max\{ x \in A : x < M \} \). If no such \( x \) exists, output -1.

inputFormat

The first line contains a single integer \( n \), 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, which is the second largest distinct element in the array. If it does not exist, output -1.

## sample
5
10 5 8 3 12
10

</p>