DP solution to K transactions


  • 0
    P
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int K = 2;
            vector<int> res(K + 1, 0), buy(K + 1, INT_MIN);
            for(int i = 0; i < prices.size(); i++){
                for(int j = K; j > 0; j--){
                    res[j] = max(res[j], buy[j] + prices[i]);
                    buy[j] = max(buy[j], res[j - 1] - prices[i]);
                }
            }
            return res[K];
        }
    };
    

Log in to reply
 

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