Leetcode Best Time to Buy and Sell Stock III 123
2016-12-29 18:57
405 查看
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) { int len=prices.size(); if(len==0 || len==1) return 0; if(len==2){ if(prices[1]>prices[0]) return prices[1]-prices[0]; else return 0; } vector<int> lsum(len+1,0); vector<int> rsum(len+1,0); int min_=prices[0]; int mp=0; int maxprice=0; for(int i=0;i<len;i++){ if(prices[i]<min_) min_=prices[i]; mp=prices[i]-min_; if(mp>maxprice) maxprice=mp; lsum[i]=maxprice; } int max_=prices[len-1]; mp=0; maxprice=0; for(int i=len-1;i>=0;i--){ if(prices[i]>max_) max_=prices[i]; mp=max_-prices[i]; if(mp>maxprice) maxprice=mp; rsum[i]=maxprice; } int temp=lsum[0]+rsum[1]; for(int i=1;i<len-1;i++){ if(temp<(lsum[i]+rsum[i+1])){ temp=lsum[i]+rsum[i+1]; } } for(int i=0;i<len;i++){ if(temp<lsum[i]) temp=lsum[i]; if(temp<rsum[i]) temp=rsum[i]; } return temp; } };
相关文章推荐
- LeetCode(123) Best Time to Buy and Sell Stock III (Java)
- 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
- LeetCode123:Best Time to Buy and Sell Stock III
- [Leetcode 123, Hard] 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(c++)
- Best Time to Buy and Sell Stock III - LeetCode 123
- LeetCode: Best Time to Buy and Sell Stock III [123]
- LeetCode 123 Best Time to Buy and Sell Stock III
- Java for LeetCode 123 Best Time to Buy and Sell Stock III【HARD】
- 123 Best Time to Buy and Sell Stock III [Leetcode]
- 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
- leetcode123---Best Time to Buy and Sell Stock III
- Leetcode_123_Best Time to Buy and Sell Stock III