@xzhang22 said in Is it Best Solution with O(n), O(1).:

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

Thanks for the analysis. The key to understand it is:

1.maxProfit2 is the max value of the sum of the 2 transactions.

2."lowestBuyPrice2 actually is not the exact price of the one we bought the stock in the second transactoin."

Or we can just think this way:

"maxProfit2" = gainIn2ndTransaction + maxProfit1

= sellPrice2 - buyPrice2 + maxProfit1

= sellPrice2 - (buyPrice2 - maxProfit1)

So "lowestBuyPrice2" is really "(buyPrice2 - maxProfit1)". This is the origin of the following code:

lowestBuyPrice2 = Math.min(lowestBuyPrice2, p-maxProfit1);