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

最佳买卖股票时机含冷冻期。还是股票系列中的一道题。给的还是一个表示每天股价的数组,还是要求返回最大收益。这道题多的一个条件是在每次卖出后需要有一天的冷冻期。

思路依然是动态规划。这道题的动态规划的定义方式跟前几道题的定义方式类似,这里我们需要一个二维数组 dp[i][j] ,第一维表示第几天,第二维表示在某种状态下(持有股票,卖出股票,冷冻期间)的最大值。最后返回的是最后一天不持有股票和最后一天是冷冻期两者之间的较大值。其余部分请参见代码注释。这里同时附上一个讲的非常好的题解

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int maxProfit(int[] prices) {
 3         int len = prices.length;
 4         // corner case
 5         if (len < 2) {
 6             return 0;
 7         }
 8 
 9         // dp[i][j] - i是第几天,j是是否持股的状态
10         // j有0,1,2三种状态,分别表示不持股,持股,冷冻期
11         int[][] dp = new int[len][3];
12         // 初始化
13         dp[0][0] = 0;
14         dp[0][1] = -prices[0];
15         dp[0][2] = 0;
16         for (int i = 1; i < len; i++) {
17             dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
18             dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][2] - prices[i]);
19             dp[i][2] = dp[i - 1][0];
20         }
21         return Math.max(dp[len - 1][0], dp[len - 1][2]);
22     }
23 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13703500.html