Say you have an array for which the i thelement is the price of a given stock on dayi.
Design an algorithm to find the maximum profit. You may complete at most twotransactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题意:股票最多能卖两次,求最大收益;
思路:动态规划,以第i天为分界线,计算第i天之前进行一次交易的最大收益pre[i],和第i天之后进行一次交易最大收益postProfit[i]
最后遍历一遍max(pre[i]+post[i])最大值
class Solution
{
int maxProfit(vector<int> &prices)
{
if (prices.size()<=1)
{
return 0;
}
int n = prices.size();
int * preProfit = new int[n]();
int * postProfit = new int[n]();
int curMin = prices[0];
for (int i=1; i<n; i++)
{
curMin = min(curMin, prices[i]);
preProfit[i] = max(preProfit[i-1], prices[i]-curMin);
}
int curMax = prices[n-1];
for (int i=n-2; i>=0; i--)
{
curMax = max(curMax, prices[i]);
postProfit[i] = max(postProfit[i + 1], curMax - prices[i]);
}
int maxProfit = 0;
for (int i = 0; i<n; i++)
{
maxProfit = max(maxProfit, postProfit[i] + preProfit[i]);
}
delete[] postProfit;
delete[] preProfit;
return maxProfit;
}
};