309. Best Time to Buy and Sell Stock with Cooldown

本文介绍了一种用于计算股票交易最大利润的算法。该算法允许多次买卖操作,并考虑了冷却期限制,即卖出后不能立即购买。通过动态规划方法,跟踪买入和卖出的最佳时机,实现了利益最大化。

摘要生成于 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)

Example:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

Credits:


public class Solution {
    public int maxProfit(int[] prices) {

        
        //buy[i]=max(buy[i-1],sell[i-2]-prices[i])在当前节点买入和之前所有可能买入节点的最大值
        //sell[i]=max(sell[i-1],buy[i-1]+prices[i])在当前结点卖出和此节点以前所有节点卖出的最大值
        //当前的buy和sell的最大值依赖前一个和前2个 
        
        int n=prices.length; 
        //初始值,在刚刚开始时,之前的卖出得到的利润为0;之前的买入最大利润为负数的最大值。因为刚刚开始不可能是卖。
        int pre_buy,buy=Integer.MIN_VALUE,pre_sell=0,sell=0;
        //pre表示前一天买入和卖出,buy和sell表示当天买入和卖出
        for(int i=0;i<n;i++){
            pre_buy=buy;
            buy=Math.max(pre_buy,pre_sell-prices[i]);
            pre_sell=sell;
            sell=Math.max(sell,pre_buy+prices[i]);
        }
        return sell;
        
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值