#151 Best Time to Buy and Sell Stock III
来源:互联网 发布:糯米商家怎么收费知乎 编辑:程序博客网 时间:2024/06/05 22:38
题目描述:
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.
Notice
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Given an example [4,4,6,1,1,4,2,5]
, return 6
.
这题的思路和#149一样。刚开始的时候我想把149的函数直接拿过来用,对于每个i都两边算一个single max profit,然后求得交易两次的profit。这个方法可行,可是时间代价是O(n^2)完全不能accept。
这题根据forward-backward traversal的提示,应该想到不但max/min number可以这么干,profit也可以用同样的思路求:对于每个i,可以左边求一个profit,右边求一个profit,然后两边相加看哪个i对应的总和最大。
例如左边求profit,需要一个left_min数组记录i往左的最小值,i是当前的price,而且永远在最小值左边。这样,一直往右遍历i,找到prices[i] - left_min[i]的最大值就可以了。
Mycode(AC = 39ms):
class Solution {public: /** * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here if (prices.size() <= 1) return 0; vector<int> left_min(prices), left_profit(prices.size(), 0); vector<int> right_max(prices), right_profit(prices.size(), 0); // get left min and left profit for (int i = 1; i < prices.size(); i++) { left_min[i] = min(left_min[i - 1], prices[i]); left_profit[i] = max(left_profit[i - 1], prices[i] - left_min[i]); } // get right max and right profit for (int i = prices.size() - 2; i >= 0; i--) { right_max[i] = max(right_max[i + 1], prices[i]); right_profit[i] = max(right_profit[i + 1], right_max[i] - prices[i]); } int profit = 0; for (int i = 0; i < prices.size(); i++) { profit = max(profit, left_profit[i] + right_profit[i]); } return profit; }};
- #151 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] 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
- 中国剩余定理(孙子定理)及实现----原理详解
- Eclipse使用Maven创建Web时错误:Could not resolve archetype org.apache.maven.archetypes:maven-archetype-webap
- 如何嵌入并自动化 Word 文档的 MFC-微软官方文档
- KConfig、Makefile详解
- Swift-->CocoaPods的使用与安装
- #151 Best Time to Buy and Sell Stock III
- 2015年蓝桥杯省赛C组
- 利用jQuery ui dialog 显示表单对话框通用JS方法
- 客户结算类型
- 集合相关内容
- JSONObject can't be resolved to a type解决办法
- static 关键字
- c语言-文件io
- Android 使用SystemBarTint设置状态栏颜色