Middle-题目19:309. Best Time to Buy and Sell Stock with Cooldown

本文介绍了一种带有 cooldown 限制的股票买卖算法。该算法允许进行多次交易但每次卖出后会有冷却期,在此期间不能再次购买。通过维护两个 DP 数组 buy 和 sell 实现最大利润的计算。

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

题目原文:
Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
题目大意:
Middle-题目4相同,区别是卖出股票之后会有一天的CD(冷却期),而在CD的时候是不能买入的。求最大利益。
题目分析:
维护两个dp数组buy和sell,其中buy代表第n天时手里有股票的收益,sell代表第n天时手里无股票的收益。
接下来的转移方程不是很好想到:
buy[i] = max(sell[i-2]-price[i],buy[i-1])
第i天时手里有股票,这时候看第i-1天在做什么:
(1) 如果是买入,则第i天要想手里有股票,什么也不能做,此时buy[i]=buy[i-1].
(2) 如果是卖出,则第i天是CD,啥也干不了,手里一定是没有股票的,这种情况无解。
(3) 如果什么也没做,则第i-2天把股票卖了,手里没股票,并在第i天买入。此时buy[i]=sell[i-2]+price[i]
Sell[i] = max(buy[i-1]+price[i],sell[i-1])
故buy[i]是两者的最大值。
第i天时手里没有股票,这时候还是看第i-1天在做什么:
(1) 如果是买入,则第i-1天是买入,第i天卖掉,此时sell[i]=buy[i-1]+price[i]
(2) 如果是卖出,则第i天是cd,此时sell[i]=sell[i-1]
(3) 如果啥也没做,而手里有股票,还是sell[i]=sell[i-1]
同理sell[i]也是两者最大值。
最后的最大利益是sell[i]的值。因为到最后必须把股票卖了。
因为只跟前两项有关系,所以也是维护两项即可。
源码:(language:java)

public class Solution {
    public int maxProfit(int[] prices) {
        int buy=-999999,preBuy=0,sell=0,preSell=0;
        for(int price : prices) {
            preBuy = buy;
            buy = Math.max(preSell - price, preBuy);
            preSell = sell;
            sell = Math.max(preBuy + price, preSell);
        }
        return sell;       
    }
}

成绩:
1ms,beats 87.89%,众数2ms,40.16%
Cmershen的碎碎念:
DP问题的关键是找出转移数组和转移方程。而这道题的转移方程对我来说比较难想,应多注意。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值