ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2020-09-21 06:01:12  阅读:296  来源: 互联网

标签:Sell 309 Buy int len buy sell prices dp


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 题目总结

标签:Sell,309,Buy,int,len,buy,sell,prices,dp
来源: https://www.cnblogs.com/cnoodle/p/13703500.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有