欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

动态规划-309. Best Time to Buy and Sell Stock with Cooldown

程序员文章站 2022-06-17 18:26:21
...
题目:

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]

题意解读:给定一个数组,数组的第i各元素就是第i天的股票的价格。你可以有任意多的交易次数。但是有两点限制,①你必须在卖出之后才能重新购买

②再卖出股票之后,你不能在第二天购买股票。至少要休息一天

动态规划-309. Best Time to Buy and Sell Stock with Cooldown

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0) return 0;
        //定义三种状态数组 s0,s1,s2
        int[] s0 = new int[prices.length];//状态s2和状态s0休息之后进入s0
        int[] s1 = new int[prices.length];//状态s0购买股票或者状态s1休息进入s1
        int[] s2 = new int[prices.length];//状态s1卖出股票进入s2
        
        //初始化三种状态
        s0[0] = 0;//一开始,如果你并没有任何股票,休息之后,还是0
        s1[0] = -prices[0];//买进prices[0]。所以是-price[0]
        s2[0] = 0;//一开始并没有拥有股票,所以不存在卖出。所以是0
        
        for(int i = 1; i < prices.length; i++){
            s0[i] = Math.max(s0[i-1],s2[i-1]);
            s1[i] = Math.max(s0[i-1] - prices[i],s1[i-1]);
            s2[i] = s1[i-1] + prices[i];
        }
        
        return Math.max(s0[prices.length-1],s2[prices.length-1]);
    }
}


相关标签: 动态规划