I agree with the logic of your method but there is no need to do recursive processing or global maxima searches. To find the sell/buy days you just need to look at each day once:
The trick is to start from the end. Stock trade is easy if your travel backwards in time!
If you think code is easier to read than words, just skip my explanation, but here goes:
Reading from the end, look at price of that day. Is this the highest price so far (from the end), then sell! The last day (where we start reading) you will always sell.
Then go to the next day (remember, backwards in time). Is it the highest price so far (from all we looked at yet)? - Then sell all, you will not find a better day. Else the prices increase, so buy. continue the same way until the beginning.
The whole problem is solved with one single reverse loop: calculating both the decisions and the profit of the trade.
Here's the code in C-like python: (I avoided most pythonic stuff. Should be readable for a C person)
def calcprofit(stockvalues):
dobuy=[1]*len(stockvalues) # 1 for buy, 0 for sell
prof=0
m=0
for i in reversed(range(len(stockvalues))):
ai=stockvalues[i] # shorthand name
if m<=ai:
dobuy[i]=0
m=ai
prof+=m-ai
return (prof,dobuy)
Examples:
calcprofit([1,3,1,2]) gives (3, [1, 0, 1, 0])
calcprofit([1,2,100]) gives (197, [1, 1, 0])
calcprofit([5,3,2]) gives (0, [0, 0, 0])
calcprofit([31,312,3,35,33,3,44,123,126,2,4,1]) gives
(798, [1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0])
Note that m
is the highest stock price we have seen (from the end). If ai==m
then the profit from stocks bought at the the step is 0: we had decreasing or stable price after that point and did not buy.
You can verify that the profit calculation is correct with a simple loop (for simplicity imagine it's within the above function)
stock=0
money=0
for i in range(len(stockvalues)):
if dobuy[i]:
stock+=1
money-=stockvalues[i]
else:
money+=stockvalues[i]*stock
stock=0
print("profit was: ",money)