111_leetcode_Best Time to Buy and Sell Stock III
来源:互联网 发布:精准客源数据下载 编辑:程序博客网 时间:2024/06/06 00:56
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).
int maxProfit(vector<int> &prices) { if(prices.size() <= 1) { return 0; } int size = (int)prices.size(); vector<int> leftProfit(size, 0); leftProfit[0] = 0; int minValue = prices[0]; int result = 0; for(int i = 1; i < size; i++) { if(prices[i] > minValue) { leftProfit[i] = (prices[i] - minValue > leftProfit[i-1] ? prices[i] - minValue : leftProfit[i-1]); } else { minValue = prices[i]; leftProfit[i] = leftProfit[i-1]; } } result = leftProfit[size-1] > leftProfit[size-2] ? leftProfit[size-2] : leftProfit[size-1]; int maxValue = prices[size -1]; int rightMaxProfit = 0; for(int i = size - 2; i >= 0; i--) { if(prices[i] < maxValue) { rightMaxProfit = (rightMaxProfit > maxValue - prices[i] ? rightMaxProfit : maxValue - prices[i]); } else { maxValue = prices[i]; } if(i == 0) { result = (result > rightMaxProfit ? result : rightMaxProfit); } else { result = (result > rightMaxProfit + leftProfit[i-1] ? result : rightMaxProfit + leftProfit[i-1]); } } return result; }
0 0
- 111_leetcode_Best Time to Buy and Sell Stock III
- 99_leetcode_Best Time to Buy and sell Stock
- 110_leetcode_Best Time to Buy and sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- leetcode 62: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- 优游平台总代最新的网址【总代Q941494533】搅
- javascript自执行函数
- AMQP协议
- 关于windows系统桌面右下角出现不是正版提示水印的解决办法
- C++ 习题 比较大小-类模板
- 111_leetcode_Best Time to Buy and Sell Stock III
- T4 模板 : 一种提升ASP.NET MVC开发速度方法
- ubuntu 安装cx_Oracle
- mysql timestamp
- Lucene近实时搜索
- zTree实例
- C#遍历访问Dictionary和HashTable
- 融资百万美元的YO是个什么东东?
- css初始化代码方案