作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/

题目描述

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的能力还是太弱,越是这样越需要迎难而上。

这个题和714. Best Time to Buy and Sell Stock with Transaction Fee比较像。做题方法都是使用了两个数组:

  1. cash 该天结束手里没有股票的情况下,已经获得的最大收益
  2. hold 该天结束手里股票的情况下,已经获得的最大收益

状态转移方程式这样的:

cash[i]代表的是手里没有股票的收益,这种可能性是今天卖了或者啥也没干。max(昨天手里有股票的收益+今天卖股票的收益,昨天手里没有股票的收益), 即max(sell[i - 1], hold[i - 1] + prices[i]);
hold[i]代表的是手里有股票的收益,这种可能性是今天买了股票或者啥也没干,今天买股票必须昨天休息。所以为max(今天买股票是前天卖掉股票的收益-今天股票的价格,昨天手里有股票的收益)。即max(hold[i - 1], sell[i - 2] - prices[i])。

另外需要注意的是,题目说的是昨天卖了股票的话今天不能买,对于开始的第一天,不可能有卖股票的行为,所以需要做个判断。

该算法的时间复杂度是O(n),空间复杂度是O(n)。

代码如下:

class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices: return 0
sell = [0] * len(prices)
hold = [0] * len(prices)
hold[0] = -prices[0]
for i in range(1, len(prices)):
sell[i] = max(sell[i - 1], hold[i - 1] + prices[i])
hold[i] = max(hold[i - 1], (sell[i - 2] if i >= 2 else 0) - prices[i])
return sell[-1]

如果使用O(1)的空间复杂度,那么就可以写成下面这样:

class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices: return 0
prev_sell = 0
curr_sell = 0
hold = -prices[0]
for i in range(1, len(prices)):
temp = curr_sell
curr_sell = max(curr_sell, hold + prices[i])
hold = max(hold, (prev_sell if i >= 2 else 0) - prices[i])
prev_sell = temp
return curr_sell

C++解法如下:

class Solution {
public:
int maxProfit(vector<int>& prices) {
const int N = prices.size();
if (N == 0) return 0;
// cash[i] means the max profit if I dont have stock on day i
vector<int> cash(N, 0);
// stock[i] means the max profit if I have stock on day i
vector<int> stock(N, 0);
stock[0] = -prices[0];
for (int i = 1; i < N; i++) {
cash[i] = max(stock[i - 1] + prices[i], cash[i - 1]);
stock[i] = max((i >= 2 ? cash[i - 2] : 0) - prices[i], stock[i - 1]);
}
return cash[N - 1];
}
};

参考资料:

https://soulmachine.gitbooks.io/algorithm-essentials/java/dp/best-time-to-buy-and-sell-stock-with-cooldown.html

日期

2018 年 9 月 12 日 —— 做题还是要有耐心
2019 年 1 月 3 日 —— 2019年已经过去1%

【LeetCode】309. Best Time to Buy and Sell Stock with Cooldown 解题报告(Python & C++)的更多相关文章

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

  2. LeetCode 309. Best Time to Buy and Sell Stock with Cooldown (stock problem)

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

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

  4. [leetcode] 309. Best Time to Buy and Sell Stock with Cooldown(medium)

    原题 思路: 状态转移 出售股票的状态,最大利润有两种可能. 一,和昨天一样不动:二,昨天持有的股票今天卖掉. sell[i] = max(sell[i-1],buy[i-1] + prices[i] ...

  5. LeetCode 309 Best Time to Buy and Sell Stock with Cooldown 解决方案

    题目描述 给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 .​ 设计一个算法计算出最大利润.在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票): 你不能同时参与多笔 ...

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

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

随机推荐

  1. ctfshow WEB入门 信息收集 1-20

    web1 题目:开发注释未及时删除 查看页面源代码即可 web2 题目:js把鼠标右键和f12屏蔽了 方法一: 禁用JavaScript 方法二: url前面加上view-source: web3 题 ...

  2. MapReduce的类型与格式

    MapReduce的类型 默认的MR作业 默认的mapper是Mapper类,它将输入的键和值原封不动地写到输出中 默认的partitioner是HashPartitioner,它对每条记录的键进行哈 ...

  3. TCP中的TIME_WAIT状态

    TIME_WAIT的存在有两大理由 1.可靠地实现TCP全双工连接的终止 2.允许老的可重复分节在网络中消失. 对于理由1,我们知道TCP结束需要四次挥手,若最后一次的客户端的挥手ACK丢失(假设是客 ...

  4. Android实现网络监听

    一.Android Wifi常用广播 网络开发中主体会使用到的action: ConnectivityManager.CONNECTIVITY_ACTION WifiManager.WIFI_STAT ...

  5. Output of C++ Program | Set 13

    Predict the output of following C++ program. 1 #include<iostream> 2 using namespace std; 3 4 c ...

  6. ANTLR 简介

    <ANTLR 4权威指南>由机械工业出版社出版,有兴趣的读者推荐购买阅读. 本专题大多内容来源于我读<ANTLR 4权威指南>的随手笔记以及个人实践,仅供参考学习,请勿用于任何 ...

  7. hooks中,useEffect无限调用问题产生的原因

    前言:我在我的另一篇博客中有说道useEffect监听对象或者数组时会导致useEffect无限执行,并给予了解决方案-useEffect无限调用问题 .后来我想从其产生根源去理解并解决这个问题. 原 ...

  8. Linux_ShellCode总结

    在寄存器都是非理想值情况下(shellcode可根据环境具体触发时寄存器的值做长度调整),我本着最优通用的原则,整理了Linux下32位和64位最短通用shellcode的编写. 32位 有" ...

  9. 【01】SpringBoot2核心技术-基础入门

    SpringBoot 2 1. SpringBoot2核心技术-基础入门 01 Spring与SpringBoot 1.Spring 能做什么 1.1 Spring的能力 微服务:将一个应用的所有功能 ...

  10. Python+Robot Framework实现UDS诊断自动化测试

    一.环境搭建 1.概述 由于项目需要进行UDS诊断测试,所以对这方面进行了研究学习,网上很少能查询到相关资料,故记录一下UDS自动化测试开发过程,由于保密原则,案例都是Demo,希望能帮到感兴趣的朋友 ...