#P5682. Strictly Second Maximum Modulo
Strictly Second Maximum Modulo
Strictly Second Maximum Modulo
Alice has n positive integers denoted as \(a_1, a_2, \dots, a_n\). Bob, who has just learned about the modulo operation, computes the value of
\[
a_i \bmod a_j \quad (1 \le i, j \le n \;\wedge\; i \neq j),
\]
where \(\bmod\) denotes the modulo operation. After computing all possible values (where the same numerical result is counted only once), Alice is interested in finding the strictly second largest value among these distinct results.
Note: For any two numbers \(x\) and \(y\) with \(x < y\), notice that \(x \bmod y = x\), so all numbers less than the maximum element appear in the result set when taken modulo the maximum. However, some pairs, especially those involving the overall maximum, can produce different remainders. In particular, let \(M\) be the maximum value in the array, \(S\) be the largest number less than \(M\), and let \(R\) be the second largest number (if it exists) among those less than \(M\). Then, the distinct modulo results include both \(S\) (from any \(x \bmod M = x\) with \(x < M\)) and \(M \bmod S\). The answer is defined as the second largest value in this set, i.e. \(\max( R, M \bmod S )\), where if there is no \(R\) (when there is only one distinct number less than \(M\)), the answer is simply \(M \bmod S\).
inputFormat
The first line of input contains a single integer \(n\) (\(n \ge 2\)), representing the number of positive integers. The second line contains \(n\) space-separated positive integers \(a_1, a_2, \dots, a_n\).
outputFormat
Output a single integer – the strictly second largest distinct value among all values of \(a_i \bmod a_j\) (for \(i \neq j\)).
sample
3
5 3 1
2