leetcode[123]Best Time to Buy and Sell Stock III
2015-02-09 13:15
627 查看
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).
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).
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.size()==0)return 0; int n=prices.size(); vector<int> left(n); vector<int> right(n); int min=prices[0]; int max=prices[n-1]; int res=0; for(int i=1;i<n;i++) { min=min<prices[i]?min:prices[i]; left[i]=left[i-1]>(prices[i]-min)?left[i-1]:(prices[i]-min); } for(int j=n-2;j>=0;j--) { max=max>prices[j]?max:prices[j]; right[j]=right[j+1]>(max-prices[j])?right[j+1]:(max-prices[j]); } for(int i=0;i<n;i++) { res=res>(left[i]+right[i])?res:(left[i]+right[i]); } return res; } };
相关文章推荐
- leetcode || 123、Best Time to Buy and Sell Stock III
- Leetcode_123_Best Time to Buy and Sell Stock III
- [LeetCode 123] - 买入与卖出股票的最佳时机III(Best Time to Buy and Sell Stock III)
- [leetcode-123]Best Time to Buy and Sell Stock III(c++)
- [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
- leetcode123---Best Time to Buy and Sell Stock III
- 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
- Java for LeetCode 123 Best Time to Buy and Sell Stock III【HARD】
- LeetCode: Best Time to Buy and Sell Stock III [123]
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode123:Best Time to Buy and Sell Stock III
- leetcode解题报告:123 Best Time to Buy and Sell Stock III