#C12318. Maximum Difference
Maximum Difference
Maximum Difference
Given an array of integers, your task is to compute the maximum difference between any two elements in the array such that the larger element appears after the smaller element. Formally, you need to calculate
\(\max_{j>i}\left(a_j - a_i\right)\) (in \(\LaTeX\) format) for all valid \(i, j\). If no such pair exists or if the array contains less than two elements, output -1.
This problem tests your ability to traverse arrays while keeping track of minimum elements seen so far and efficiently computing the required difference.
inputFormat
The input consists of two lines:
- The first line contains an integer \(n\), representing the number of elements in the array.
- The second line contains \(n\) space-separated integers.
If \(n < 2\), the answer is automatically \(-1\).
outputFormat
Output a single integer representing the maximum difference between two elements where the larger element appears after the smaller element. If no such pair exists, output \(-1\).
## sample4
7 1 5 4
4