The various stock prices of an item during various points throughout the day are given in this text . What is the maximum profit you can get if you are allowed to perform at most two buys and at most two sells?
Details and Assumptions
You can only buy another stock if you have sold the one you bought previously.
As an explicit example if the stock prices are
[2, 4, 5, 6, 9, 5, 4, 3, 8]
you buy at
and sell at
, and you buy another stock at
and sell at
. for a max profit of
[8, 7, 5, 4, 3, 2]
there will be no profit, as the value of the stock is decreasing with time.
The stock prices are sequential with respect to time, so that you can only buy or sell only the stock at hand.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Let the price be p ( n ) , then the two transactions for maximum profit are:
Buy at p ( 3 3 ) = p ( 7 6 ) = p ( 9 5 ) = 5 and see at p ( 1 0 3 ) = 9 8 and profit = 9 3 . Note that 1 0 3 > 9 5 > 7 6 > 3 3 .
Buy at p ( 1 6 4 > 1 0 3 ) = 3 and sell at p ( 1 9 3 > 1 6 4 ) = 9 9 and profit = 9 6 .
The total profit is 1 8 9 .
Again I used an Excel spreadsheet.