#K67397. Maximum Difference Problem

    ID: 32633 Type: Default 1000ms 256MiB

Maximum Difference Problem

Maximum Difference Problem

Given a sequence of integers, find the maximum difference between any two elements such that the larger element appears after the smaller element in the sequence.

Mathematically, you need to compute:

\[ \max_{0 \le i < j < n} (a_j - a_i) \]

If no such pair exists (for example, when the list is empty or has only one element, or is sorted in non-increasing order), output 0.

Example: For the array [7, 1, 5, 3, 6, 4], the maximum difference is 5, which comes from the pair (1, 6).

inputFormat

The first line contains a single integer \( n \) representing the number of elements in the array. The second line contains \( n \) space-separated integers forming the array.

outputFormat

A single integer representing the maximum difference between any two elements where the larger comes after the smaller. If no valid pair exists, output 0.

## sample
6
7 1 5 3 6 4
5