309. Best Time to Buy and Sell Stock with Cooldown
2016-06-27 22:32
417 查看
Problem
Say you have an array for which the ithelement 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]
Solution
讨论区的解答There are three states, according to the action that you can take.
Hence, from there, you can now the profit at a state at time i as:
s0[i] = max(s0[i - 1], s2[i - 1]); // Stay at s0, or rest from s2
s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); // Stay at s1, or buyfrom s0
s2[i] = s1[i - 1] + prices[i]; // Only one way from s1
Then, you just find the maximum of s0
and s2
, since they will be the maximum profit we need (No one can buy stock and left with more profit that sell right :) )
Define base case:
s0[0] = 0; // At the start, you don’t have any stock if you just rest
s1[0] = -prices[0]; // After buy, you should have -prices[0] profit.Be positive!
s2[0] = INT_MIN; // Lower base case
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() <= 1) return 0; int n = prices.size(); vector<int> s0(n,0); vector<int> s1(n,0); vector<int> s2(n,0); s0[0] = 0; s1[0] = -prices[0]; s2[0] = INT_MIN; for(int i = 1;i<n;++i) { s0[i] = max(s0[i - 1], s2[i - 1]); s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); s2[i] = s1[i - 1] + prices[i]; } return max(s0[prices.size() - 1], s2[prices.size() - 1]); } };
相关文章推荐
- Android support library支持包常用控件介绍(二)
- Android support library支持包常用控件介绍(二)
- 《Windows程序设计》读书笔六 键盘
- 高德地图获取开发所需要的key
- js如何判断客户端类型
- golang中的channel
- VARCHAR2的简单说明
- springmvc mybatis 基于全注解事务配置注意事项
- 算法:特殊二维数组查询key值是否存在
- js如何判断客户端类型
- MyBatis学习总结(三)——优化MyBatis配置文件中的配置
- ubuntu 分卷
- 并不能ac jsoi2009
- HDU 1222 Wolf and Rabbit(gcd)
- gperftools编译与使用
- 秦始皇的国家道路系统
- 汇编语言 王爽 第二版 实验15
- 归并排序空间复杂度O(1)的实现
- 1002
- 线程池