Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next N days.
Each day, you can either buy one share of WOT, or sell any number of shares of WOT that you own. What is the maximum profit you can obtain with an optimum trading strategy?
Input
The first line contains the number of test cases T. T test cases follow:
The first line of each test case contains a number N. The next line contains N integers, denoting the predicted price of WOT shares for the next N days.
Output
Output T lines, containing the maximum profit which can be obtained for the corresponding test case.
Constraints
1 <= T <= 10
1 <= N <= 50000
All share prices are between 1 and 100000
Sample Input
3
3
5 3 2
3
1 2 100
4
1 3 1 2
Sample Output
0
197
3
Explanation
For the first case, you cannot obtain any profit because the share price never rises. For the second case, you can buy one share on the first two days, and sell both of them on the third day.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t; cin>>t; while(t--){ int n; cin>>n; vector<int> price(n); for(int i = 0; i< n ;++i) cin>>price[i]; vector<int> left_max(n); int max = 0; for(int i = n - 1; i >= 0; --i){ if(price[i] > max) max = price[i]; left_max[i] = max; } long long total = 0; for(int i = 0; i< n; ++i){ if(left_max[i] > price[i]) total += left_max[i] - price[i]; } cout<<total<<endl; } return 0; }