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

来源:互联网 发布:qq业务乐园源码 编辑:程序博客网 时间:2024/06/07 03:29
题目:

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 = 3transactions = [buy, sell, cooldown, buy, sell]

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

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


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]);    }}


原创粉丝点击