leetcode-309. Best Time to Buy and Sell Stock with Cooldown
2016-05-02 01:11
501 查看
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:
Example:
思路:这道题学习自Share my DP solution (By State Machine Thinking),思路是DP+状态机,看了就懂了,浅显易懂,醍醐灌顶
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:
思路:这道题学习自Share my DP solution (By State Machine Thinking),思路是DP+状态机,看了就懂了,浅显易懂,醍醐灌顶
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() < 1) { return 0; } //reset vector<int> s0(prices.size(),0); //buy vector<int> s1(prices.size(),0); //sell vector<int> s2(prices.size(),0); s0[0] = 0; s1[0] = -prices[0]; s2[0] = INT_MIN; for(int i=1;i < prices.size();i++) { s0[i] = max(s0[i-1],s2[i-1]); s1[i] = max(s1[i-1],s0[i-1]-prices[i]); s2[i] = max(s2[i-1],s1[i-1]+prices[i]); } return max(s0[prices.size()-1],s2[prices.size()-1]); } };
相关文章推荐
- 深度分析C++默认构造函数、拷贝构造函数
- Python+Apache环境安装与配置
- 用本地电脑调试tomcat服务器时,先看好自己本机的ip地址
- Create Started Service
- redis之其他
- Top Data Scientists to Follow & Best Data Science Tutorials on GitHub
- AndroidStudio中使用Git上传项目到github(非常详细,非常全面)(by 星空武哥)
- InstallShield Limited Edition制作安装文件
- Java高级之反射(一)
- pwntools安装使用方法
- ConcurrentHashMap 内部实现分析
- MFC实现窗体透明
- 模拟实现strchr和strrchr
- LeetCode 13. Roman to Integer
- InstallShield制作升级安装包
- Faster RNNLM (HS/NCE) toolkit
- 浅谈 Scrapy 爬虫(二)
- myeclips如何与mysql建立连接
- Python处理JSON
- 三行代码实现Android彷腾讯视频播放界面的登陆框悬浮(吸附)在视频的底部