首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Array - 309. Best Time to Buy and Sell Stock with Cooldown

Array - 309. Best Time to Buy and Sell Stock with Cooldown

作者头像
ppxai
发布2020-09-23 17:55:14
发布2020-09-23 17:55:14
3480
举报
文章被收录于专栏:皮皮星球皮皮星球
  1. 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:

Input: [1,2,3,0,2] Output: 3 Explanation: transactions = [buy, sell, cooldown, buy, sell]

视频讲解: https://www.bilibili.com/video/bv1bT4y1g76h

思路:

继续是买卖股票的变形题,这一题的多加了一个条件,就是卖完股票得要等一天(cooldown)才可以继续买股票。采用动态规划求解。

  1. 定义两个状态 hold[i]unhold[i]分别表示第i天hold股票的最大盈利和不hold股票的最大盈利。
  2. 目标是unhold[n-1] (n为交易天数)
  3. base case hold[0] = -prices[0]hold[1] = max(-prices[1], -prices[0])unhold[0] = 0
  4. 状态转移 hold[i]取最大值: 1、第i天买入 unhold[i-2] - prices[i] 2、第i天没有买入 hold[i-1] unhold[i]取最大值: 1、第i天卖出 hold[i-1] + prices[i] 2、第i天没有卖出 unhold[i-1]

代码:

java:

代码语言:javascript
复制
class Solution {

    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) return 0;
        
        int len = prices.length;
        int[] hold = new int[len];
        int[] unhold = new int[len];
        
        
        hold[0] = -prices[0];
        
        for (int i = 1; i < len; i++) {
            if (i == 1) {
                hold[i] = Math.max(hold[i-1], -prices[i]);
            } else {
                hold[i] = Math.max(hold[i-1], unhold[i-2] - prices[i]);
            }
            
            unhold[i] = Math.max(unhold[i-1], hold[i-1] + prices[i]);
        }
        
        return unhold[len-1];        
    }

}

go:

代码语言:javascript
复制
func maxProfit(prices []int) int {
    if prices == nil || len(prices) == 0 {
        return 0
    }
    
    var hold = make([]int, len(prices))
    var unhold = make([]int, len(prices))
    
    hold[0] = -prices[0]
    
    for i := 1; i < len(prices); i++ {
        if i == 1 {
            hold[i] = max(-prices[1], hold[0])
        } else {
            hold[i] = max(unhold[i-2] - prices[i], hold[i-1])
        }
        
        unhold[i] = max(hold[i-1] + prices[i], unhold[i-1])
    }
    
    return unhold[len(prices) - 1]
}


func max(i, j int) int {
    if i > j {
        return i
    }
    return j
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020年05月31日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档