Leetcode 题解 - 动态规划-股票交易(1):需要冷却期的股票交易

[LeetCode] 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]

 

这是股票系列问题中目前来看最难的一个,不过有了前面几个问题的思路,这个问题求解起来非常容易。首先,我们看到问题中提到了三种状态buy、sell和cooldown,那么我们脑中的第一个想法就是通过动态规划来解

如果我们index:i天为冷冻期,那么只能说明index:i-1天卖掉了股票,那么i天的收益和i-1天是一样的

cooldown[i]=sell[i-1]
如果我们考虑index:i天卖出,要求利润最大的话。一种情况是index:i-1当天买入了股票,另一种情况是index:i-1之前就持有股票,index:i-1天也可以卖出,那么我们就需要考虑index:i-1卖出更好呢?还是index:i卖出更好呢?

sell[i]=max(sell[i-1], buy[i-1]+prices[i])
如果我们考虑index:i天买入,要求利润最大的话。一种情况是index:i-1天是冷冻期,另一种情况是index:i-1天不是冷冻期,也就是index:i-1天也可以买入,那么我们就需要考虑index:i-1买入更好呢?还是index:i买入更好呢?

buy[i]=max(buy[i-1], cooldown[i-1]-prices[i])
我们第一天不可能卖出或者冻结,那么这两个sell[0]=0 cooldown[0]=0,但是我们第一天可以买入啊,所以buy[0]=-prices[0]。还有一点要注意的就是,我们一定是最后一天卖出或者最后一天冻结利润最大。
 

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0)
            return 0;
        int n = prices.length;
        int[] buy = new int[n];
        int[] sell = new int[n];
        int[] rest = new int[n];
        buy[0] = -prices[0];
        for(int i=1; i<n; i++){
            buy[i] = Math.max(buy[i-1], rest[i-1] -prices[i]);
            sell[i] = Math.max(buy[i-1] + prices[i], sell[i-1]);
            rest[i] = sell[i - 1];
        }
        return Math.max(sell[n-1], rest[n-1]);
    }
}


作者:coordinate_blog 
来源:CSDN 
原文:https://blog.csdn.net/qq_17550379/article/details/82856452 

第二次写

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        if(n == 0)
            return 0;
        int[] buy = new int[n];
        int[] sell = new int[n];
        int[] cool = new int[n];
        buy[0] = -prices[0];
        for(int i = 1; i < n; i++){
            buy[i] = Math.max(cool[i-1] - prices[i], buy[i-1]);
            sell[i] = Math.max(sell[i-1], buy[i-1] + prices[i]);
            cool[i] = sell[i - 1];
        }
        return Math.max(sell[n-1], cool[n-1]);
        
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值