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 index i. It may happen at i - 1, i - 2, ... 0.
  • In the end n - 1, return sell[n - 1]. Apparently we cannot finally end up with a buy. In that case, we would rather take a rest at n - 1.
  • For special case no transaction at all, classify it as sell[i], so that in the end, we can still return sell[n - 1]. Thanks @alex153 @kennethliaoke @anshu2.

2. Define Recursion

  • buy[i]: To make a decision whether to buy at i, we either take a rest, by just using the old decision at i - 1, or sell at/beforei - 2, then buy at i, We cannot sell at i - 1, then buy at i, because of cooldown.
  • sell[i]: To make a decision whether to sell at i, we either take a rest, by just using the old decision at i - 1, or buy at/before i - 1, then sell at i.

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, b0 represent buy[i - 2], buy[i - 1], buy[i]
  • Let s2, s1, s0 represent sell[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 = 0 ending with a buy is -prices[0].
  • We cannot sell. The max profit at i = 0 ending with a sell is 0.
 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的更多相关文章

  1. 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 题目的要求是只买卖一次,买的价格越低,卖的价格越高,肯定收益就越大 遍历整个数组,维护一个当前位置之前最低的买入价格,然后每次 ...

  2. 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. 买卖股票 ...

  3. [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 ...

  4. [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 ...

  5. 【LeetCode】309. Best Time to Buy and Sell Stock with Cooldown 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetc ...

  6. 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 ...

  7. 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 ...

  8. 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 ...

  9. 解题报告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 ...

随机推荐

  1. ASP.NET技巧:教你制做Web实时进度条

    网上已经有很多Web进度条的例子,但是很多都是估算时间,不能正真反应任务的真实进度.我自己结合多线程和ShowModalDialog制做了 一个实时进度条,原理很简单:使用线程开始长时间的任务,定义一 ...

  2. thinkphp 3.2.3 连接sql server 2014 WAMPSERVER环境包

    安装 sqlsrv 扩展 首先  sql server 2014 安装没啥说的 链接信息自己设置 php 版本 :5.5.12 sqlsrv 驱动  微软提供了 3.0 和3.1 版本  3.0 对应 ...

  3. 防SQL注入代码(ASP版)

    <% Dim Fy_Url,Fy_a,Fy_x,Fy_Cs(),Fy_Cl,Fy_Ts,Fy_Zx '---定义部份 头------ Fy_Cl = 1 '处理方式:1=提示信息,2=转向页面, ...

  4. 史上最全的maven pom.xml文件教程详解

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  5. thinkphp的url地址区分大小写?

    在默认情况下: 在访问url地址的时候, 其中的 Action类名 即: 模块名称 是区分大小写的. (只有模块名, 即控制器名称) 可以根据设置 'URL_CASE_INSENSITIVE' =&g ...

  6. ConcurrentHashMap-----不安全线程hashmap-安全线程-hashtable

    JDK1.0引入了第一个关联的集合类HashTable,它是线程安全的.HashTable的所有方法都是同步的.JDK2.0引入了HashMap,它提供了一个不同步的基类和一个同步的包装器synchr ...

  7. solr6.1-----mysql 数据导入-查询

    此部分一定要细心,lz 中间错了一个细节,调了好长时间(汗).请严格按照步骤操作 新建core 步骤1: 在webapps中solrhome下新建一个文件夹名字叫做collection1(名字不固定, ...

  8. javascript简单的认识下return语句+2015的总结+2016的展望

    好久没更新博客了...自从有了mac之后世界变得简单了...日常么,除了研究代码,看别人的代码,写自己的代码.就那样.... 吐槽点:window配个nodejs的环境花了九头牛两只老虎的力气,mac ...

  9. AngularJS API之bootstrap启动

    对于一般的使用者来说,AngularJS的ng-app都是手动绑定到某个dom元素.但是在一些应用中,这样就显得很不方便了. 绑定初始化 通过绑定来进行angular的初始化,会把js代码侵入到htm ...

  10. SharePoint Server 2010 中的基本任务

    SharePoint Foundation 和 SharePoint Server 概述 SharePoint Foundation 2010 是一项用于 SharePoint 网站的基础技术,它可以 ...