[309] Best Time to Buy and Sell Stock with Cooldown

本文介绍了一种算法,用于解决股票交易中如何最大化利润的问题。该算法考虑了限制条件,如不能同时进行多笔交易及卖出后一天内不可再买进等。通过动态规划的方法实现了最优解。

【题目描述】

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]
【解题思路】

参考https://discuss.leetcode.com/topic/30421/share-my-thinking-process

【代码】

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buy=INT_MIN,sell=0,prev_sell=0,prev_buy=0;
        for(int i=0;i<prices.size();i++){
            prev_buy=buy;
            buy=max(prev_sell-prices[i],prev_buy);
            prev_sell=sell;
            sell=max(prev_buy+prices[i],prev_sell);
        }
        return sell;
    }
};


### 使用 Python 解决买卖股票最佳时机问题 以下是对 LeetCode 上的几个经典股票买卖问题的算法和代码实现: #### 1. 仅允许一次交易(Best Time to Buy and Sell Stock) 对于只允许进行一次买入和一次卖出的操作,可以通过一次遍历数组来找到最大利润。核心思想是记录当前遍历到的最低价格,并计算以当前价格卖出的利润,同时更新最大利润。 ```python def maxProfit(prices): if not prices: return 0 min_price = prices[0] max_profit = 0 for price in prices: if price < min_price: min_price = price # 更新最低价格 elif price - min_price > max_profit: max_profit = price - min_price # 更新最大利润 return max_profit ``` 上述代码的时间复杂度为 \(O(n)\),空间复杂度为 \(O(1)\)[^5]。 #### 2. 允许多次交易(Best Time to Buy and Sell Stock II) 当允许多次买入和卖出时,只要后一天的价格高于前一天的价格,就可以在每一天都进行交易以获得最大利润。通过累加所有递增区间的差值即可得到结果。 ```python def maxProfit(prices): total_profit = 0 for i in range(1, len(prices)): if prices[i] > prices[i - 1]: total_profit += prices[i] - prices[i - 1] # 累加利润 return total_profit ``` 该算法的时间复杂度为 \(O(n)\),空间复杂度为 \(O(1)\)[^3]。 #### 3. 带有冷却期的多次交易(Best Time to Buy and Sell Stock with Cooldown) 在这种情况下,需要考虑冷却期的限制。可以使用动态规划解决此问题。定义状态 `dp[i][0]` 表示第 \(i\) 天不持有股票的最大利润,`dp[i][1]` 表示第 \(i\) 天持有股票的最大利润。 ```python def maxProfit(prices): if not prices: return 0 n = len(prices) dp = [[0, 0] for _ in range(n)] dp[0][0] = 0 dp[0][1] = -prices[0] for i in range(1, n): dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]) # 不持有股票 dp[i][1] = max(dp[i - 1][1], dp[i - 2][0] - prices[i] if i > 1 else dp[i - 1][0] - prices[i]) # 持有股票 return dp[-1][0] ``` 此算法的时间复杂度为 \(O(n)\),空间复杂度为 \(O(n)\)[^2]。 ### 总结 以上三种方法分别适用于不同的股票交易场景。第一种适用于只能进行一次交易的情况,第二种适用于允许多次交易但无冷却期的情况,第三种则适用于带有冷却期的多次交易情况。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值