leetcode 309. Best Time to Buy and Sell Stock with Cooldown

本文探讨了在股票买卖中,考虑到卖出后必须休息一天的规则下,如何通过动态规划算法实现最大收益。通过状态转移方程,定义了买入、卖出和休息三种状态,并用滚动数组优化空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

买股票,中间买卖完一次后必须休息一下,求最大收益

题解

建议观看视频 ->->->-> https://www.bilibili.com/video/av31578180

状态转移图
1172239-20190804174650974-15237438.png

buy[i] 代表当前持有股票的最大收益
sell[i] 代表当前卖出股票的最大收益
rest[i] 代表当前休息的最大收益

class Solution {
public:
    // buy[i] -> util day i hold the stock max profit
    // sell[i] -> util day i sell the stock i max profit
    // rest[i] -> util day i rest max profit
    int maxProfit(vector<int>& prices) {
        const int INF = 0x3f3f3f3f;
        int len = prices.size();
        int buy[len+1] = {0};
        int sell[len+1] = {0};
        int rest[len+1] = {0};
        buy[0] = -INF; rest[0] = 0; sell[0] = 0;
        for(int i=1; i<=len; i++) {
            buy[i] = max(buy[i-1], rest[i-1] - prices[i-1]);
            sell[i] = prices[i-1] + buy[i-1];
            rest[i] = max(rest[i-1], sell[i-1]);
        }
        return max(sell[len], rest[len]);
    }
};

滚动数组优化空间

class Solution {
public:
    // buy[i] -> util day i hold the stock max profit
    // sell[i] -> util day i sell the stock i max profit
    // rest[i] -> util day i rest max profit
    int maxProfit(vector<int>& prices) {
        const int INF = 0x3f3f3f3f;
        int len = prices.size();
        int buy[2] = {0};
        int sell[2] = {0};
        int rest[2] = {0};
        buy[0] = -INF; rest[0] = 0; sell[0] = 0;
        for(int i=1; i<=len; i++) {
            buy[i % 2] = max(buy[(i-1) % 2], rest[(i-1) % 2] - prices[i-1]);
            sell[i % 2] = prices[i-1] + buy[(i-1) % 2];
            rest[i % 2] = max(rest[(i-1) % 2], sell[(i-1) % 2]);
        }
        return max(sell[len%2], rest[len%2]);
    }
};

转载于:https://www.cnblogs.com/Draymonder/p/11298982.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值