leetcode-309: 最佳买卖股票时机含冷冻期

参考博客:LeetCode 309: 一个很清晰的DP解题思路

生动形象,图解一目了然

题目传送:309. 最佳买卖股票时机含冷冻期

类似于《逻辑与计算机设计基础》中的状态图,根据状态图写出转化方程:

s[i] = Math.max(s[i-1], sell[i-1]);
buy[i] = Math.max(buy[i-1], s[i-1]-prices[i]);
sell[i] = buy[i-1]+prices[i];

s[i],buy[i],sell[i] 分别表示最后一次操作是冷冻,买,卖的利益的最大值。

完整代码:

// 最佳买卖股票时机 (含冷冻期)
class Solution {
    public int maxProfit(int[] prices) {
    	int len = prices.length;
        if(prices == null || len == 0) return 0;
        int[] s = new int[len];
        int[] buy = new int[len];
        int[] sell = new int[len];
        // 分别表示最后一天是 冷冻期, 买, 卖的最大收益

        buy[0] = -prices[0];
        s[0] = 0;
        sell[0] = 0;

        for(int i = 1; i < len; i++) {
        	s[i] = Math.max(s[i-1], sell[i-1]);
        	buy[i] = Math.max(buy[i-1], s[i-1]-prices[i]);
        	sell[i] = buy[i-1]+prices[i];
        }

        return Math.max(buy[len-1], Math.max(sell[len-1], s[len-1]));
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值