#C12303. Maximum Difference in Array
Maximum Difference in Array
Maximum Difference in Array
Given an array of integers, your task is to compute the maximum difference between two elements such that the larger element appears after the smaller element in the array. Formally, you need to find:
$$\max_{0\le i < j < n}(a_j - a_i)$$
If no such pair exists (i.e. the array is sorted in non-increasing order or there is only one element), output -1
.
inputFormat
The input is read from standard input and contains two lines:
- The first line contains a single integer
n
which denotes the number of elements in the array. - The second line contains
n
space-separated integers representing the elements of the array.
Note: If n < 2
, you should directly output -1
since no valid pair exists.
outputFormat
Output a single integer to standard output which is the maximum difference between two elements satisfying the condition, or -1
if it does not exist.
6
7 1 5 3 6 4
5