您的位置:首页 > 其它

Best Time to Buy and Sell Stock III

2014-04-11 20:10 176 查看
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).

可以买两次。

如果只是两次,确实很好做。两个数组记录该点前最大利润和该点后的最大利润,然后找出利润和最大的点便可。log n。

class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
vector<int> before(n,0);
vector<int> after(n,0);

for(int i = 1 ; i < n ;i++)
{
if(prices[i]-prices[i-1]+before[i-1]>0)
before[i]= prices[i]-prices[i-1]+before[i-1];
else
before[i] = 0;
}
for(int i = n-2 ; i >= 0 ;i--)
{
if(prices[i+1] -prices[i] + after[i+1] > 0 )
after[i] = prices[i+1] -prices[i] + after[i+1];
else
after[i] = 0;
}
int max =0;
for(int i = 1; i < n ; i++)
{
if(before[i]<before[i-1])before[i]=before[i-1];
}
for(int i= n-2;i>=0;i--)
{
if(after[i]<after[i+1])after[i]=after[i+1];
}
for(int i = 0 ; i < n ; i++)
{
if(before[i] + after[i] > max)
max = before[i] + after[i];
}
return max;

}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: