相关问题1:[LeetCode] Best Time to Buy and Sell Stock II
相关问题2:[LeetCode] Best Time to Buy and Sell Stock VI
给你一个数组,数组的每个元素表示每天的stock价格,你最多可以进行2次交易,两次交易不能在时间上重叠,也就是说,你必须先卖掉股票,才能再买入股票。求可以获得的最大利润。 该问题还可以扩展为:把最多2次交易的条件,改成最多k次交易。
思路:可以把数组分成两部分,求出前一个部分的max_profit_left,再求出后一个部分的max_profit_right,最后求出 max_profit_left + max_profit_right 所能达到的最大值。
代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<=1) return 0;
vector<int> maxP_left(prices.size(),0);
vector<int> maxP_right(prices.size(),0);
int minPrice = prices.front();
for(int i=0; i<prices.size(); i++)
{
minPrice = min(minPrice, prices[i]);
if(i==0)
maxP_left[i] = prices[i]-minPrice;
else
maxP_left[i] = max( maxP_left[i-1], prices[i]-minPrice );
}
int maxPrice = prices.back();
for(int i=prices.size()-1; i>=0; i--)
{
maxPrice = max(maxPrice, prices[i]);
maxP_right[i] = maxPrice - prices[i];
if(i==prices.size()-1)
maxP_right[i] = maxPrice - prices[i];
else
maxP_right[i] = max( maxP_right[i+1], maxPrice - prices[i] );
}
int maxP = 0;
for(int i=0; i<prices.size(); i++)
{
maxP = max(maxP, maxP_left[i]+maxP_right[i]);
}
return maxP;
}
};