LeetCode 309. 最佳买卖股票时机含冷冻期

leetcode acwing

动态规划 \(O(3n)\)

状态机DP,第一次碰见

image-20210105104715086

C++ 代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty()) return 0;
        int n = prices.size();
        vector<vector<int>> f(n, vector<int>(3, -1e8));

        // 初始状态
        f[0][0] = 0, f[0][1] = -prices[0];

        for (int i = 1; i < n; i ++)
        {
            f[i][0] = max(f[i - 1][0], f[i - 1][2]);
            f[i][1] = max(f[i - 1][0] - prices[i], f[i - 1][1]);
            f[i][2] = f[i - 1][1] + prices[i];
        }

        return max(f[n - 1][0], max(f[n - 1][1], f[n - 1][2]));
    }
}
posted @ 2021-01-05 10:49  alexemey  阅读(41)  评论(0)    收藏  举报