Editorial
Let be the stock prices over the days. Compute — the maximum on the suffixes of the array . If we buy a share at price on the -th day, then in the future, we can profitably sell it at the highest price , gaining a profit of . We need to compute the total profit, which is equal to
Example
Let’s consider the second test. Compute the maximum on the suffixes of the array of stock prices.
For example, on the first day, we buy a share for , and later sell it for (the sale will occur on the third day).
The total profit will be .
Algorithm realization
Read the input data.
scanf("%d", &n); p.resize(n); dp.resize(n); for (i = 0; i < n; i++) scanf("%d", &p[i]);
Compute .
dp[n - 1] = p[n - 1]; for (i = n - 2; i >= 0; i--) dp[i] = max(p[i], dp[i + 1]);
Compute the total profit . On the -th day, we buy a share at price , and later sell it for , gaining a profit of .
res = 0; for (i = 0; i < n; i++) res = res + dp[i] - p[i];
Print the answer.
printf("%lld\n", res);
Python realization
Read the input data.
n = int(input()) p = list(map(int, input().split()))
Compute .
dp = [0] * n dp[n - 1] = p[n - 1] for i in range(n - 2, -1, -1): dp[i] = max(p[i], dp[i + 1])
Compute the total profit . On the -th day, we buy a share at price , and later sell it for , gaining a profit of .
res = 0 for i in range(n): res += dp[i] - p[i]
Print the answer.
print(res)