LeetCode 309. 最佳买卖股票时机含冷冻期(动态规划)

1. 题目

给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​

设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

  • 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
  • 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:
输入: [1,2,3,0,2]
输出: 3 
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

类似题目:
LeetCode 121. 买卖股票的最佳时机
LeetCode 122. 买卖股票的最佳时机 II
LeetCode 123. 买卖股票的最佳时机 III(动态规划)
LeetCode 188. 买卖股票的最佳时机 IV(动态规划)
LeetCode 714. 买卖股票的最佳时机含手续费(DP)

  • dp[i][0]表示第 i 天不持有股票的最大收益
  • dp[i][1]表示第 i 天持有股票的最大收益
  • 跟第二题很接近。
class Solution {
public:
    int maxProfit(vector<int>& prices) {
    	if(prices.size() <= 1)
    		return 0;
    	int i, n = prices.size();
        vector<vector<int>> dp(n,vector<int>(2,0));
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        dp[1][0] = max(dp[0][0], dp[0][1]+prices[1]);
        dp[1][1] = max(dp[0][1], dp[0][0]-prices[1]);
        for(i = 2; i < n; ++i)
        {
            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]);
                        // 休息,       前2天没股票,买入,要隔一天
        }
        return dp[n-1][0];
    }
};

8 ms 12 MB

原创文章 1007 获赞 3578 访问量 54万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/105858950