#C7597. Maximum Difference

    ID: 51485 Type: Default 1000ms 256MiB

Maximum Difference

Maximum Difference

Given a sequence of integers, find the maximum difference between any two elements such that the larger element appears after the smaller one. Formally, for a sequence \(a_1, a_2, \dots, a_n\), compute \(\max\{a_j - a_i \mid 1 \leq i < j \leq n\}\). If no such pair exists (for example, when the sequence is empty or has only one element, or if every element is non-increasing), output 0.

Example:

Input:
6
7 1 5 3 6 4

Output: 5

</p>

In the above example, the maximum difference is achieved by subtracting 1 from 6 to yield 5.

inputFormat

The input consists of two lines:

  • The first line contains an integer \(n\) denoting the number of elements in the sequence.
  • The second line contains \(n\) space-separated integers representing the sequence. If \(n = 0\), the second line may be omitted.

outputFormat

Output a single integer, which is the maximum difference between any two elements such that the larger element appears after the smaller one. If no valid pair exists, output 0.

## sample
6
7 1 5 3 6 4
5