【动态规划】买卖股票的最佳时机Ⅲ

题目链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/description/

cpp 复制代码
class Solution {
public:
    const int INF = 0x3f3f3f3f;
    int maxProfit(vector<int>& prices) 
    {
        /*时空复杂度O(n)*/
        int n = prices.size();
        // 1. 创建dp表
        vector<vector<int>> f(n, vector<int>(3, -INF));
        auto g = f;
        // 2. 初始化
        f[0][0] = -prices[0], g[0][0] = 0;
        // 3. 填表
        for (int i = 1; i < n; ++i)
            for (int j = 0; j < 3; ++j)
            {
                f[i][j] = max(f[i - 1][j], g[i - 1][j] - prices[i]);
                g[i][j] = g[i - 1][j];
                if (j >= 1) g[i][j] = max(g[i - 1][j], f[i - 1][j - 1] + prices[i]);
            }
        // 4. 返回值
        // return max(g[n - 1][0], max(g[n - 1][1], g[n - 1][2]));
        int ret = 0;
        for (int j = 0; j < 3; ++j)
            ret = max(ret, g[n - 1][j]);
        return ret;
    }
};
相关推荐
稚南城才子,乌衣巷风流2 小时前
ST 表(Sparse Table)算法详解:原理、实现与应用
算法
hold?fish:palm2 小时前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle2 小时前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木2 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
不会就选b3 小时前
算法日常・每日刷题--<归并排序>1
数据结构·算法
危桥带雨3 小时前
排序算法(快排、归并、计数、基数排序)
数据结构·算法·排序算法
啦啦啦啦啦zzzz3 小时前
算法:回溯算法
c++·算法·leetcode
IT探索3 小时前
Linux 查找文件指令总结
linux·算法
攻城狮Soar3 小时前
C++子类访问父类成员
c++·算法