Best Time to Buy and Sell Stock III
来源:互联网 发布:fikker破解版linux 编辑:程序博客网 时间:2024/06/06 10:39
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:
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).
思路:在整个过程中至多进行两次交易,求得最大的获取收益的价值。可以这样考虑,整个数组以prices[i]为分界线,前[0...i]中获得一个最大的profit.后面[i...prices.size()-1]的控件内再获得一个最大的profit。两者之和就是整个数组的最大的收益。每一部分求得最大收益的方式和这个类型I的解决方式一致。
具体代码如下所示:
class Solution {public: int maxProfit(vector<int>& prices) { if(prices.size()<2)//此时的条件不成立 return 0; int low=prices[0]; int res=0; vector<int>leftProfit(prices.size(),0); for(int i=1;i<prices.size();i++) { if(prices[i]<low) low=prices[i]; res=res>prices[i]-low?res:prices[i]-low; leftProfit[i]=res; } //从后向前来计算 int high=prices[prices.size()-1]; int rightres=0; res=0; for(int i=prices.size()-2;i>=0;i--) { if(prices[i]>high) high=prices[i]; rightres=rightres>high-prices[i]?rightres:high-prices[i]; res=res>rightres+leftProfit[i]?res:rightres+leftProfit[i]; } return res; }};
0 0
- 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
- 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
- 使用开单引号对SQL语句中的表字段名转义
- linux vps下mysql cpu占用过高解决办法
- 交叉编译nanopi QT+QWT界面的流程和问题
- [hadoop]hadoop eclipse plugin安装与配置(四)
- Android使用Cordova框架开发Android Hybrid App
- Best Time to Buy and Sell Stock III
- (二)Hyper如何对DataBlock中的数据进行索引
- 将pgm图片使用Sequence file存储到hdfs,并读取为Mat数组格式
- 后缀数组模板
- java编写网页爬虫(分页——插入数据库——导出数据)
- Sublime Text 3 常用插件以及安装方法
- 定制自己的报表!7款实用开源报表工具
- UIAutomator定位Android控件的方法实践和建议(Appium姊妹篇)
- Java经典类库-Guava中的函数式编程讲解