#K7726. Maximum Difference in an Array

    ID: 34825 Type: Default 1000ms 256MiB

Maximum Difference in an Array

Maximum Difference in an Array

Given an array of integers, your task is to find the maximum difference ( d = a_j - a_i ) such that ( i < j ) (i.e., the smaller element comes before the larger one). If there is no valid pair (for example, when the array is non-increasing or has fewer than two elements), output (-1).

The intended approach is to traverse the list only once by keeping track of the minimum element seen so far and updating the maximum difference accordingly.

inputFormat

The input is given via standard input (stdin).

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 output should be (-1).

outputFormat

Output a single integer to standard output (stdout), which is the maximum difference ( a_j - a_i ) for any ( i < j ). If no such pair exists, output (-1).## sample

6
7 1 5 3 6 4
5