Thursday, March 10, 2016

LeetCode Q123: Best Time to Buy and Sell Stock III (hard)

Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Solution:
Two passes. One forward, one backward.
In forward pass, compute the highest profit could get if sell the stock before and including current day.
In backward pass, compute the highest profit could get if sell the stock after and including the current day.
Add results of two passes and return the maximum.


Solution 2:
The thinking is simple and is inspired by the best solution from Single Number II (I read through the discussion after I use DP). Assume we only have 0 money at first; 4 Variables to maintain some interested 'ceilings' so far: The maximum of if we've just buy 1st stock, if we've just sold 1nd stock, if we've just buy 2nd stock, if we've just sold 2nd stock. Very simple code too and work well. I have to say the logic is simple than those in Single Number II.

So, in following code, the lowestBuyPrice1 and maxProfit1 are very easy to understand. The only thing that may take time to understand is the computation of lowestBuyPrice2. Here lowestBuyPrice2 actually is not the exact price of the one we bought the stock in the second transactoin. Actually, it contains two parts if we can open it as *lowestBuyPrice2* = buyPrice2 - maxProfit1 = buyPrice2 - (highestSellPrice1 - lowestBuyPrice1). So you will see, *lowestBuyPrice2* contains the buy price of 2nd transaction as well as the profit we obtained for the 1st transaction. When we compute *maxProfit2* = sellPrice2 - lowestBuyPrice2 = sellPrice2 - buyPrice2 + maxProfit1 = profitOf2ndTrans + maxProfit1. So, at the end of computation, *maxProfit2* will contain profits for both transactions.




No comments:

Post a Comment