[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

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

Example 2:

Input: prices = [1]
Output: 0

Constraints:

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000

最佳买卖股票时机含冷冻期。

给定一个整数数组prices,其中第  prices[i] 表示第 i 天的股票价格 。​

设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

思路依然是动态规划。这道题的动态规划的定义方式跟前几道题的定义方式类似,这里我们需要一个二维数组 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         // 0:持有现金
 9         // 1:持有股票
10         // 状态转移:0 → 1 → 0 → 1 → 0 → 1 → 0
11         int[][] dp = new int[len][3];
12         // 第一天不持有股票,收益就是0;买了股票,收益就是-prices[0],可理解为成本
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             // 今天不持有股票的收益来自于昨天不持有股票或今天卖了股票之后的较大值
18             dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
19             // 今天持有股票的收益来自于昨天持有股票或过了冷冻期之后可以买股票的较大值
20             dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][2] - prices[i]);
21             // 今天如果是冷冻期,那么收益是来自于昨天不持有股票
22             dp[i][2] = dp[i - 1][0];
23         }
24         return Math.max(dp[len - 1][0], dp[len - 1][2]);
25     }
26 }

 

LeetCode 题目总结

posted @ 2020-09-21 05:48  CNoodle  阅读(369)  评论(0编辑  收藏  举报