A short and clean C++ solution


  • 2
    E
    class Solution
    {
    public:
        int maxProfit(vector<int> &prices)
        {
            if (prices.empty())
            {
                return 0;
            }
    
            auto buy = -prices.front();
            auto sell1 = 0;
            auto sell2 = 0;
    
            for (size_t i = 1; i < prices.size(); ++i)
            {
                tie(buy, sell1, sell2) = make_tuple(max(buy, sell2 - prices[i]), max(sell1, buy + prices[i]), sell1);
            }
    
            return sell1;
        }
    };
    

    I use std::tie to avoid extra variables.


Log in to reply
 

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