Best Time to Buy and Sell Stock II
来源:互联网 发布:虚拟机怎么安装mac os 编辑:程序博客网 时间:2024/04/28 23:29
本题属于动态dp,
buy表示到目前i为止最后一个状态是买(有可能之前买的最近一直没卖,有可能是刚买的)
sell表示到目前i为止最后一个状态是卖(有可能之前卖了最近一直没买,有可能刚卖的)
注意一下两个递推公式:
buy=max(buy,sell-prices[i]);
sell=max(sell,buy+prices[i]);
另外,要找到开始的buy和sell,当找到递增部分即可。
AC代码:
<pre name="code" class="cpp">class Solution {public:int maxProfit(vector<int>& prices) {int buy=0,sell=0,j=0;if(prices.size()>1){ //判断下初始的buy 和sellfor(;j<prices.size()-1;j++){if(prices[j+1]>prices[j]){buy=-prices[j];sell=prices[j+1]-prices[j];break;}}for(int i=j+2;i<prices.size();i++){buy=max(buy,sell-prices[i]);sell=max(sell,buy+prices[i]);} }return sell;}};
0 0
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- I/O模型
- CentOS Linux下VNC Server远程桌面配置详解
- 基于java容器注解说明---@Value和@ImportResource
- SSM报错:java.sql.SQLException: 无效的列类型: 1111
- ASP.NET MVC设计原则讲解
- Best Time to Buy and Sell Stock II
- getenv()
- Sparse Table算法+poj3264(Balanced line up)题解----倍增思想
- Find Peak Element解题报告
- FAT 工作原理
- Spring+JMS+ActiveMQ+Tomcat实现消息服务
- IE10中下拉框 title被遮挡以及部分option无法显示的问题
- sql语句大全
- SolrJ的使用