Alice is trying to earn money in the stocks.
In the following $n$ days, she can choose one day to buy in and one day after buying in to sell out, she may also not operate at all.
Somehow, Alice has accessed internal information about the value of the stock every day, she knows that the value of the stock after $i$ days is $a_i$.
Now she wants to know how much money she can earn if she buys and sells optimally.
Input
Line $1$, an integer $n$.
Line $2$, $n$ integers, the $i$-th integer represents $a_i$.
Output
One Line, one number representing the answer.
Constraints
For all test cases: $n \le 5 \cdot 10^{5}$, $1 \le a_i \le 10^{9}$.
Subtask $1$: Array $a$ is non-increasing ($10$ points)
Subtask $2$: Array $a$ is non-decreasing ($12$ points)
Subtask $3$: $n \le 5000$ ($28$ points)
Subtask $4$: There exists an optimal way of operating such that Alice sells when the stock is the most expensive ($24$ points)
Subtask $5$: No Additional Constraints ($26$ points)
Sample Test Cases
| Input | Output | |
|---|---|---|
| 5 5 2 4 1 3 |
2 | |
| 4 11 4 51 4 |
47 |
Scoring: Per Subtask
Authored by s23f32
Appeared in 2026 Mini Comp 2