HackerRank: Stock Maximize
https://codepair.hackerrank.com/paper/ug5kzwn8?b=eyJyb2xlIjoiY2FuZGlkYXRlIiwibmFtZSI6ImplZmZlcnl5dWFuIiwiZW1haWwiOiJ5dWFueXVuLmtlbm55QGdtYWlsLmNvbSJ9
long last = arr[n-1];
for(int i=n-1;i>=0;i--){
if(arr[i] > last) last = arr[i]; // else
ans += last - arr[i];
}
ww.println(ans);
https://codepair.hackerrank.com/paper/zLx7APyG?b=eyJyb2xlIjoiY2FuZGlkYXRlIiwibmFtZSI6ImplZmZlcnl5dWFuIiwiZW1haWwiOiJ5dWFueXVuLmtlbm55QGdtYWlsLmNvbSJ9
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, sell any number of shares of WOT that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?
[1, 7, 2, 4, 5, 9, 1, 2, 6]
We should buy 1, 7, 2, 4, 5. Then sell all these five stocks at the point 9, get the profit of 8 + 2 + 7 + 5 + 4 = 26. After that, buy 1, 2. Sell them at 6, get the profit of 5 + 4 = 9. The total profit is then 35.
int
max_current_future_price = 0;
ll profit = 0;
for
(
int
i=size-1; i>=0; --i) {
max_current_future_price = max(max_current_future_price, stock_price[i]);
profit += (ll)max_current_future_price - stock_price[i];
}
long last = arr[n-1];
for(int i=n-1;i>=0;i--){
if(arr[i] > last) last = arr[i]; // else
ans += last - arr[i];
}
ww.println(ans);
https://codepair.hackerrank.com/paper/zLx7APyG?b=eyJyb2xlIjoiY2FuZGlkYXRlIiwibmFtZSI6ImplZmZlcnl5dWFuIiwiZW1haWwiOiJ5dWFueXVuLmtlbm55QGdtYWlsLmNvbSJ9