Ripple Effect
Maged has dropped out of his computer science degree after seeing the slumps in the job market, and is now hoping to make it big as a crypto day trader. He is hoping to analyse past trends in his favorite cryptocurrency, XRP, in order to make it big in the future.
Maged has recorded the price of XRP at regular intervals into an array called . He is interested in a measure he calls "volatility", where volatility over a given time interval (subarray
) is given by the highest price in that interval, minus the lowest price — in other words,
.
He hopes to understand the market more by summing all the volatility values over all consecutive subarrays in his dataset , as every price change is a missed opportunity for profit.
Input
The first line contains a single integer
, the number of data points in Maged's dataset
.
The next line contains space-separated integers
, representing the values in the dataset
.
Output
The "volatility" value of an array is determined by its maximum value subtracted by its minimum value. Output the sum of the volatility values of all consecutive subarrays of .
Example
Input 1
5
1 10 3 8 9
Output 1
69
We can enumerate all possible subarrays and their values as follows. Note that 1-element subarrays will always contribute .
1 10
:1 10 3
:1 10 3 8
:1 10 3 8 9
:10 3
:10 3 8
:10 3 8 9
:3 8
:3 8 9
:8 9
:
Input 2
8
1 2 3 4 10 9 8 7
Output 2
140
Comments