LeetCode(123) Best Time to Buy and Sell Stock III
来源:互联网 发布:qq模仿哪个软件 编辑:程序博客网 时间:2024/05/21 06:55
题目
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).
Subscribe to see which companies asked this question
分析
紧接着121 和122 的另外一道题目,此次要求只能进行两次买卖交易,求最大利润。
一篇很好的分析文章,参考博客。
第一步扫描,先计算出子序列[0,…,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。
计算方法也是利用第一个问题的计算方法。
第二步是逆向扫描,计算子序列[i,…,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。
第三步,求[0,i]的最大利润与[i,n-1]的最大利润之和的最大值,所以最后算法的复杂度就是O(n)的。
AC代码
class Solution {public: int maxProfit(vector<int>& prices) { if (prices.empty()) return 0; int n = prices.size(); vector<int> profits(n, 0), profits_reverse(n,0); //正向遍历,profits[i]表示 prices[0...i]内做一次交易的最大收益. int low = prices[0] , cur_profit = 0; for (int i = 1; i < n; ++i) { if (prices[i] < low) { low = prices[i]; } else{ if (cur_profit < prices[i] - low) cur_profit = prices[i] - low; } profits[i] = cur_profit; }//for //逆向遍历, profits_reverse[i]表示 prices[i...n-1]内做一次交易的最大收益. //当前最大价格 int high = prices[n - 1]; cur_profit = 0; for (int i = n - 2; i >= 0; --i) { if (prices[i] > high) high = prices[i]; else{ if (cur_profit < high - prices[i]) cur_profit = high - prices[i]; }//else profits_reverse[i] = cur_profit; } int max_profile = 0; for (int i = 0; i < n; i++) { if ((profits[i] + profits_reverse[i]) > max_profile) max_profile = profits[i] + profits_reverse[i]; } return max_profile; }};
GitHub测试程序源码
0 0
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III [123]
- LeetCode 123 Best Time to Buy and Sell Stock III
- [leetcode 123] Best Time to Buy and Sell Stock III
- leetcode || 123、Best Time to Buy and Sell Stock III
- leetcode-123 Best Time to Buy and Sell Stock III
- leetcode 123: Best Time to Buy and Sell Stock III
- 123 Best Time to Buy and Sell Stock III [Leetcode]
- Best Time to Buy and Sell Stock III - LeetCode 123
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- LeetCode 123 -- Best Time to Buy and Sell Stock III
- Leetcode 123 Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- Leetcode Best Time to Buy and Sell Stock III 123
- [Leetcode 123] Best Time to Buy and Sell Stock III
- **Leetcode 123 Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- 苹果开发 笔记(85)UIActionSheet 和UIAlertView 已经失效
- View的touch事件分发。
- Directx11 HelloWorld之HLSL的Effect框架的使用
- UUID of GATT descriptor
- Android 等待进度条
- LeetCode(123) Best Time to Buy and Sell Stock III
- 自动避障小车
- 黑马程序员--面试题(1)交通灯系统
- Spring Security教程(12)---- 使用数据库来管理方法
- Eclipse怎样把文件系统形式的项目作为工程直接导入?
- 高性能单例模式
- java通过web配置监听启动定时任务
- JavaScript原型及原型链详解
- 5.Android 开发工具ADT下载