Buttercola: Zenefits: [OA]Stock Maximize
Read full article from Buttercola: Zenefits: [OA]Stock Maximize
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?
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.
The problem looks very similar to the best time to buy and sell stock. The mainly difference is in the best time to buy and sell stock, you can only hold one share of the stock. In this problem, however, you can hold as many shares as you want. But each day, you can only buy one stock, and sell any you want.
So the idea for this problem is starting from the last day N, iterate in backward order. Each time mark the highest price so far, denoting, max1, when we see a higher price, i.e, max2 > max1. Then we perform transactions between the two days. That is, buy all stocks after max2 and sell all on day max1.
public
static
long
stockMaximize(
long
[] prices) {
if
(prices ==
null
|| prices.length <=
1
) {
return
0
;
}
int
n = prices.length;
long
maxPrice = Long.MIN_VALUE;
long
maxProfit =
0
;
long
sum =
0
;
int
j = n -
1
;
for
(
int
i = n -
1
; i >=
0
; i--) {
if
(prices[i] > maxPrice) {
long
localMax = (j - i) * maxPrice - sum;
maxProfit += localMax;
j = i;
maxPrice = prices[i];
sum = prices[i];
}
else
{
sum += prices[i];
}
}
if
(j >
0
) {
maxProfit += (j +
1
) * maxPrice - sum;
}
return
maxProfit;
}