leetcode 309. Best Time to Buy and Sell Stock with Cooldown
Posted draymonder
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 309. Best Time to Buy and Sell Stock with Cooldown相关的知识,希望对你有一定的参考价值。
题意
买股票,中间买卖完一次后必须休息一下,求最大收益
题解
建议观看视频 ->->->-> https://www.bilibili.com/video/av31578180
状态转移图
buy[i] 代表当前持有股票的最大收益
sell[i] 代表当前卖出股票的最大收益
rest[i] 代表当前休息的最大收益
class Solution
public:
// buy[i] -> util day i hold the stock max profit
// sell[i] -> util day i sell the stock i max profit
// rest[i] -> util day i rest max profit
int maxProfit(vector<int>& prices)
const int INF = 0x3f3f3f3f;
int len = prices.size();
int buy[len+1] = 0;
int sell[len+1] = 0;
int rest[len+1] = 0;
buy[0] = -INF; rest[0] = 0; sell[0] = 0;
for(int i=1; i<=len; i++)
buy[i] = max(buy[i-1], rest[i-1] - prices[i-1]);
sell[i] = prices[i-1] + buy[i-1];
rest[i] = max(rest[i-1], sell[i-1]);
return max(sell[len], rest[len]);
;
滚动数组优化空间
class Solution
public:
// buy[i] -> util day i hold the stock max profit
// sell[i] -> util day i sell the stock i max profit
// rest[i] -> util day i rest max profit
int maxProfit(vector<int>& prices)
const int INF = 0x3f3f3f3f;
int len = prices.size();
int buy[2] = 0;
int sell[2] = 0;
int rest[2] = 0;
buy[0] = -INF; rest[0] = 0; sell[0] = 0;
for(int i=1; i<=len; i++)
buy[i % 2] = max(buy[(i-1) % 2], rest[(i-1) % 2] - prices[i-1]);
sell[i % 2] = prices[i-1] + buy[(i-1) % 2];
rest[i % 2] = max(rest[(i-1) % 2], sell[(i-1) % 2]);
return max(sell[len%2], rest[len%2]);
;
以上是关于leetcode 309. Best Time to Buy and Sell Stock with Cooldown的主要内容,如果未能解决你的问题,请参考以下文章