Best Time to Buy and Sell Stock III
2015-08-01 21:15
309 查看
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 at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution:
i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution:
class Solution { public: int maxProfit(vector<int>& prices) { int len = prices.size(); if(len == 0) return 0; vector<int> left(len, 0), right(len, 0); int minleft = 0, maxright = len - 1; for(int i = 1; i < len; ++i) { left[i] = max(prices[i] - prices[minleft], left[i-1]); minleft = prices[i] < prices[minleft] ? i : minleft; } for(int i = len - 2; i >= 0; --i) { right[i] = max(prices[maxright] - prices[i], right[i+1]); maxright = prices[maxright] < prices[i] ? i : maxright; } int maxprofit = 0; for(int i = 0; i < len - 1; ++i) { maxprofit = max(left[i] + right[i], maxprofit); } return maxprofit; } };
相关文章推荐
- 量化交易开发工具的选择
- 正常股市,非常股民
- ORA-01008:并非所有的变量都已绑定
- C++中接口与实现分离的技术 ZZ
- Swift对于可选类型(Optionals)讲解不错的文章
- [记录]学习<<QT学习之路2>>第五天
- HDU 2017-字符串统计
- HDU 4115 Eliminate the Conflict(2-SAT)
- Bestcoder Untitled
- 【数论】poj1811Prime Test
- 数据仓库建模与ETL的实践技巧
- Java学习之路:不走弯路,就是捷径
- 升级Android SDK后ADT找不到adb.exe文件的解决办法
- Java反射机制
- View及Viewgroup
- 黑马程序员------OC block(代码块)和protocol(协议)
- 交易基础(三)形态分析
- 用JAMES实现自己的邮件服务器
- HTTP协议
- HashSet 与 HashMap 对比