您的位置:首页 > 其它

Best Time to Buy and Sell Stock III

2015-08-01 21:15 309 查看
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).

Solution:

class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len == 0) return 0;
vector<int> left(len, 0), right(len, 0);
int minleft = 0, maxright = len - 1;
for(int i = 1; i < len; ++i)
{
left[i] = max(prices[i] - prices[minleft], left[i-1]);
minleft = prices[i] < prices[minleft] ? i : minleft;
}
for(int i = len - 2; i >= 0; --i)
{
right[i] = max(prices[maxright] - prices[i], right[i+1]);
maxright = prices[maxright] < prices[i] ? i : maxright;
}
int maxprofit = 0;
for(int i = 0; i < len - 1; ++i)
{
maxprofit = max(left[i] + right[i], maxprofit);
}

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