• LeetCode188 买卖股票的最佳时机 IV(dp)


    LeetCode188 买卖股票的最佳时机 IV

    对于第 \(i\) 只股票,可以进行的操作为作为第 \(j\) 只买入或卖出的股票

    \(buy[i][j]\) 表示对于前 \(i\) 只股票,第 \(j\) 次买入股票之后的最大收益

    \(sell[i][j]\) 表示对于前 \(i\) 只股票,第 \(j\) 次卖出股票之后的最大收益

    \(j\) 次买入股票必须在第 \(j - 1\) 次卖出股票之后发生

    这里可以使用滚动数组,优化空间复杂度

    class Solution:
        def maxProfit(self, k: int, prices: List[int]) -> int:
    
            if len(prices) == 0: return 0
            if k == 0: return 0
    
            buy, sell, l = [-prices[0]] * k, [0] * k, len(prices)
    
            for i in range(1, l):
                for j in range(k):
                    if j == 0:
                        buy[j] = max(buy[j],  -prices[i])
                        sell[j] = max(sell[j], prices[i] + buy[j])
                    else:
                        buy[j] = max(buy[j],  sell[j - 1] - prices[i])
                        sell[j] = max(sell[j], prices[i] + buy[j])
    
            return sell[k - 1]
    
    class Solution {
    public:
        int maxProfit(int k, vector<int>& prices) {
            if (prices.empty()) return 0;
            if (k == 0) return 0;
    
            int n = prices.size();
            vector<int> buy(k);
            vector<int> sell(k);
            
            for (int i = 0; i < k; ++i) {
                buy[i] = -prices[0], sell[i] = 0;
            }
    
            for (int i = 1; i < n; ++i) {
                for (int j = 0; j < k; ++j) {
                    if (j == 0) {
                        buy[j] = max(buy[j], -prices[i]);
                        sell[j] = max(sell[j], buy[j] + prices[i]);
                    } else {
                        buy[j] = max(buy[j], sell[j - 1] - prices[i]);
                        sell[j] = max(sell[j], buy[j] + prices[i]);
                    }
                }
            }
            return sell[k - 1];
        }
    };
    
  • 相关阅读:
    数据库语句学习(union语句)
    终于开通博客了啦
    Winform用Post方式打开IE
    Winform webbrowser 隐藏 html 元素
    MVC 附件在线预览
    典型用户和场景
    我的第一篇博客01
    大数据算法摘录
    mac下查看端口占用情况
    tomcat的运行脚本
  • 原文地址:https://www.cnblogs.com/solvit/p/16423904.html
Copyright © 2020-2023  润新知