leetcode有一系列买股票最佳时机问题,其中最难的当属第三道Best Time to Buy and Sell Stock III ,问题描述为:
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).
根据题干要求,最多只能有两次交易。我们很容易想到问题 Best Time to Buy and Sell Stock I,基于问题I,针对每一个交易日i,可以对其左边和右边分别DP求解问题 I,但是显然这样的时间复杂度为O(n^2)。
从另一个角度来思考这个问题,以每一个交易日i为单位,我们分别计算在这一天卖出和买进所能获得的最大收益(当然当天可以只卖出或者只买进),最后比较求出最大的一个收益即可。
下面是AC的C++代码,击败了99.47%的C++答案,说明该答案的效率很高,大家可以借鉴下。
leftmin表示第0-i天之间的最小股价;
rightmax表示第i-n-1天的最大股价;
left[i]表示第i天以及之前卖出所能获得的最大收益,递推表达式为left[i]=max(left[i-1],p[i]-leftmin);
right[i]表示第i天以及之后买入所能获得的最大收益,递推表达式为right[i]=max(right[i+1],rightmax-p[i]);
最后求全局最优解,得到最多交易两次所能获得的最大收益;
class Solution
{
public:
int maxProfit(vector<int>& p)
{
int m=p.size();
if(m<2) return 0;
int leftmin=p[0];
int rightmax=p[m-1];
vector<int> left(m,0);
vector<int> right(m,0);
for(int i=1;i<m;i++)
{
leftmin=min(leftmin,p[i]);
left[i]=max(left[i-1],p[i]-leftmin);
}
for(int j=m-2;j>=0;j--)
{
rightmax=max(rightmax,p[j]);
right[j]=max(right[j+1],rightmax-p[j]);
}
int sum=0;
for(int i=0;i<m;i++)
{
if(left[i]+right[i]>sum) sum=left[i]+right[i];
}
return sum;
}
};
希望以上解释对大家有所帮助!