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:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell] 分析:
因为当前的选择对后面的选择会产生影响,我们可以倒着来分析。
我们用maximumProfit[i]来表示从i 到 length - 1 可以获取的最大profit. 怎么计算maximumProfit[i]呢?那么对于i来讲,最坏情况是maximumProfit[i] = maximumProfit[i + 1].
然后我们把price[i]作为当前最低价,如果后面发现更高的价格price[j],我们就做出更新。
if (j < length - 2) {
maximumProfit[i] = Math.max(prices[j] - low + maximumProfit[j + 2], maximumProfit[i]);
} else {
maximumProfit[i] = Math.max(prices[j] - low, maximumProfit[i]);
}
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= )
return ;
int length = prices.length;
int[] maximumProfit = new int[length];
maximumProfit[length - ] = ;
maximumProfit[length - ] = Math.max(, prices[length - ] - prices[length - ]);
for (int i = length - ; i >= ; i--) {
maximumProfit[i] = maximumProfit[i + ];
int low = prices[i];
for (int j = i + ; j < length; j++) {
if (prices[j] > low) {
if (j < length - ) {
maximumProfit[i] = Math.max(prices[j] - low + maximumProfit[j + ], maximumProfit[i]);
} else {
maximumProfit[i] = Math.max(prices[j] - low, maximumProfit[i]);
}
} else {
low = prices[j];
}
}
}
return maximumProfit[];
}
很明显,时间总复杂度为O(n^2).
另一个方法:
Analysis: https://discuss.leetcode.com/topic/30431/easiest-java-solution-with-explanations
1. Define States
To represent the decision at index i:
buy[i]: Max profit till index i. The series of transaction is ending with a buy.sell[i]: Max profit till index i. The series of transaction is ending with a sell.
To clarify:
- Till index
i, the buy / sell action must happen and must be the last action. It may not happen at indexi. It may happen ati - 1, i - 2, ... 0. - In the end
n - 1, returnsell[n - 1]. Apparently we cannot finally end up with a buy. In that case, we would rather take a rest atn - 1. - For special case no transaction at all, classify it as
sell[i], so that in the end, we can still returnsell[n - 1]. Thanks @alex153 @kennethliaoke @anshu2.
2. Define Recursion
buy[i]: To make a decision whether to buy ati, we either take a rest, by just using the old decision ati - 1, or sell at/beforei - 2, then buy ati, We cannot sell ati - 1, then buy ati, because of cooldown.sell[i]: To make a decision whether to sell ati, we either take a rest, by just using the old decision ati - 1, or buy at/beforei - 1, then sell ati.
So we get the following formula:
buy[i] = Math.max(buy[i - 1], sell[i - 2] - prices[i]);
sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]);
3. Optimize to O(1) Space
DP solution only depending on i - 1 and i - 2 can be optimized using O(1) space.
- Let
b2, b1, b0representbuy[i - 2], buy[i - 1], buy[i] - Let
s2, s1, s0representsell[i - 2], sell[i - 1], sell[i]
Then arrays turn into Fibonacci like recursion:
b0 = Math.max(b1, s2 - prices[i]);
s0 = Math.max(s1, b1 + prices[i]);
4. Write Code in 5 Minutes
First we define the initial states at i = 0:
- We can buy. The max profit at
i = 0ending with a buy is-prices[0]. - We cannot sell. The max profit at
i = 0ending with a sell is0.
public int maxProfit(int[] prices) {
if(prices == null || prices.length <= ) return ;
int b0 = -prices[], b1 = b0;
int s0 = , s1 = , s2 = ;
for(int i = ; i < prices.length; i++) {
b0 = Math.max(b1, s2 - prices[i]);
s0 = Math.max(s1, b1 + prices[i]);
b1 = b0; s2 = s1; s1 = s0;
}
return s0;
}
Best Time to Buy and Sell Stock with Cooldown的更多相关文章
- leetcode 121. Best Time to Buy and Sell Stock 、122.Best Time to Buy and Sell Stock II 、309. Best Time to Buy and Sell Stock with Cooldown
121. Best Time to Buy and Sell Stock 题目的要求是只买卖一次,买的价格越低,卖的价格越高,肯定收益就越大 遍历整个数组,维护一个当前位置之前最低的买入价格,然后每次 ...
- Leetcode之动态规划(DP)专题-309. 最佳买卖股票时机含冷冻期(Best Time to Buy and Sell Stock with Cooldown)
Leetcode之动态规划(DP)专题-309. 最佳买卖股票时机含冷冻期(Best Time to Buy and Sell Stock with Cooldown) 股票问题: 121. 买卖股票 ...
- [LeetCode] 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 al ...
- [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 al ...
- 【LeetCode】309. Best Time to Buy and Sell Stock with Cooldown 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetc ...
- LeetCode Best Time to Buy and Sell Stock with Cooldown
原题链接在这里:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ 题目: Say you hav ...
- 121. 122. 123. 188. Best Time to Buy and Sell Stock *HARD* 309. Best Time to Buy and Sell Stock with Cooldown -- 买卖股票
121. Say you have an array for which the ith element is the price of a given stock on day i. If you ...
- 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 a ...
- 解题报告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 ...
随机推荐
- OwinStartupAttribute
尝试加载应用时出现了以下错误.- 找不到包含 OwinStartupAttribute 的程序集.- 找不到包含 Startup 或 [AssemblyName].Startup 类的程序集.若要禁用 ...
- 数据库操作事务IsolationLevel 枚举
成员名称 说明 Chaos 无法覆盖隔离级别更高的事务中的挂起的更改. ReadCommitted 在正在读取数据时保持共享锁,以避免脏读,但是在事务结束之前可以更改数据,从而导致不可重复 ...
- 登录验证码编写(jsp+servlet+dao)
一.什么是验证码及它的作用 验证码为全自动区分计算机和人类的图灵测试的缩写,是一种区分用户是计算机的公共全自动程序,这个问题可以由计算机生成并评判,但是必须只有人类才能解答. 可以防止恶意破解密码.刷 ...
- <Web 之困 现代Web应用安全指南>一本好书 69.00?
NET代码安全 界面漏洞防范与程序优化 一. SQL 注入攻击的源头 1. 过滤或转移危险字符 2. 使用SqlParameter类:.NET 框架有一个叫做SqlParameter 的集合类型,可 ...
- jq实现点击弹出框代码
废话不多说,先贴代码吧 <script> function showBg() { //定义 showBg 函数 var bh = $("body").height(); ...
- Linux下更新时间
方法一.使用命令 ntpdate time-a.nist.gov 方法二.本地安装ntpdate客户端 在本地安装ntpdate客户端,更新时用 ntpdate cn.pool.ntp.org 如果你 ...
- AngularJS 国际化——Angular-translate
对于一个用户群面向全球的的应用来说,不得不考虑国际化的问题.当然,即便是刚刚起步的小应用,如果有心搞大,也应该提前设计国际化的方案. 本篇讲述使用AngularJS构建的应用的简单国际化方案,准确的说 ...
- 【活动】不用买书,不用花钱,可以免费看HTML5入门连载了
清华大学出版社推出的<HTML 5网页开发实例详解>适合HTML 5开发初学者和前端开发工程师.本书一经上市,就获得了读者的一致好评,为感谢读者,推出本书的连载活动. 本书术新颖.与时 ...
- html 补充
替换文本属性(Alt)alt 属性用来为图像定义一串预备的可替换的文本.替换文本属性的值是用户定义的.<img src="boat.gif" alt="Big Bo ...
- cf251.2.C (构造题的技巧)
C. Devu and Partitioning of the Array time limit per test 1 second memory limit per test 256 megabyt ...