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

You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

思路
这道题不要过于在意冷静期哈,冷静期无非就是在写状态转移方程的时候,多加一个限制条件就行。
这道题可以用三个dp数组来求解。dp[ ][0]表示当天不持有股票并且没有出售股票,dp[ ][1]表示当天出售了股票所以不持有股票,dp[ ][2]表示当天持有股票。
第一种情况,前一天有可能出售了股票,也有可能没有股票也没卖过。
第二种情况,想要出售股票,前一天的状态必须是持有股票。
第三种情况,当天持有股票,可能是前一天本来既有的,也有可能是前一天买的股票。因为有冷静期的存在,因此,假如是前一天购买的股票,那么必然不是前一天购买的股票。

状态转移方程
dp[i][0] = max(dp[i-1][0], dp[i-1][1])
dp[i][1] = dp[i-1][2] + prices[i]
dp[i][2] = max(dp[i-1][2], dp[i-1][0] - prices[i])

边界条件
dp[0][0] = 0;
dp[0][1] = 0;
dp[0][2] = -prices[0];

代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int dp[30005][3];
        dp[0][0] = 0;  //不持有且没卖出去
        dp[0][1] = 0;  //不持有且卖出去了
        dp[0][2] = -prices[0];  //持有

        int len = prices.size();
        for(int i = 1; i < len; i++)
        {
            dp[i][0] = max(dp[i-1][0], dp[i-1][1]);
            dp[i][1] = dp[i-1][2] + prices[i];
            dp[i][2] = max(dp[i-1][2], dp[i-1][0] - prices[i]);
        }

        return max(dp[len-1][0], dp[len-1][1]);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值