My clean dp solution, C++ 4ms


  • 2
    Y
    int maxProfit(vector<int>& prices) 
    {
    	int buy= INT_MIN, sell_1=0,sell_2=0;
    
        for (int i = 0; i < prices.size(); ++i)
    	{
    	    buy =  i < 3 ? max(-prices[i], buy):max(sell_2-prices[i], buy);
    	    
    	    sell_2 = sell_1;
    		
    		sell_1 = max(sell_1, buy + prices[i]);
    	}
    
    	return sell_1;
    }

  • 0
    M

    Any explaination or comment heiheihei?


  • 0
    Q

    Hi,
    I feel like the "i < 3 ?" part should be " i<2 ? ", so I changed the code and submitted. It was accepted. I don't know why both are right? What do you think?
    Logically I think you are storing the past 2 days "profit" in sell_2 and sell_1, so we should be able to use generally case update for your "buy" variable from i = 2.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.