[LeetCode] Best Time to Buy and Sell Stock III

Personally, this is a relatively difficult DP problem. This link posts a typical DP solution to it. You may need some time to get how it works.

The code is rewritten as follows.

复制代码
 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int n = prices.size(), num = 2;
 5         if (n <= 1) return 0;
 6         vector<vector<int> > dp(num + 1, vector<int>(n, 0));
 7         for (int k = 1; k <= num; k++) {
 8             int temp = dp[k - 1][0] - prices[0];
 9             for (int i = 1; i < n; i++) {
10                 dp[k][i] = max(dp[k][i - 1], prices[i] + temp);
11                 temp = max(temp, dp[k - 1][i] - prices[i]);
12             }
13         }
14         return dp[num][n - 1];
15     }
16 };
复制代码

Personally, I prefer this solution, which is much easier to understand. The code is also rewritten as follows.

复制代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int states[2][4] = {INT_MIN, 0, INT_MIN, 0};
        int n = prices.size(), cur = 0, next = 1;
        for (int i = 0; i < n; i++) {
            states[next][0] = max(states[cur][0], -prices[i]);
            states[next][1] = max(states[cur][1], states[cur][0] + prices[i]);
            states[next][2] = max(states[cur][2], states[cur][1] - prices[i]);
            states[next][3] = max(states[cur][3], states[cur][2] + prices[i]);
            swap(cur, next);
        }
        return max(states[cur][1], states[cur][3]);
    }
};
复制代码

 

posted @   jianchao-li  阅读(219)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
点击右上角即可分享
微信分享提示