C++ simple solution DP


  • 0
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            vector<int> dp(5, 0);
            for (int i = 1; i < 5; i += 2)
                dp[i] = INT_MIN; //  for buying
            for (auto price : prices) {
                for (int i = 1; i < 5; i++) {
                    dp[i] = max(dp[i], dp[i - 1] + (i & 1 ? (-1 * price) : price));
                }
            }
            return dp[4];
        }
    };
    

Log in to reply
 

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