您的位置:首页 > 其它

Leetcode#123 Best Time to Buy and Sell Stock III

2015-01-21 13:08 274 查看
原题地址

最直观的想法就是划分成两个子问题,每个子问题变成了:求在某个范围内交易一次的最大利润

在只能交易一次的情况下,如何求一段时间内的最大利润?其实就是找股价最低的一天买进,然后在股价最高的一天卖出,当然,卖股票要在买股票之后。

用迭代法求这个问题非常容易,令profits[i]表示截至到第i天的最大利润,则profits[i+1] = max{profits[i], prices[i+1] - minPrice},其中,minPrice = min{prices[k]},0 <= k < n。但是从profits[i]没法直接得到profits[i-1]

倒过来迭代也完全没问题,令profits[i]表示从第i天开始到结束的最大利润,则profits[i] = max{profits[i+1], maxPrice - prices[i]},其中maxPrice = max{prices[k]},i+1 <= k < n。但是从profits[i]没法直接得到profits[i+1]

之后,依次枚举分割点,求解两个子问题的和即可。

代码:

int maxProfit(vector<int> &prices) {
int n = prices.size();
vector<int> profits(prices.size(), 0);
int result = 0;
int tmp;

if (n < 2)
return 0;

tmp = 0;
int minPrice = prices[0];
for (int i = 1; i < n; i++) {
tmp = max(tmp, prices[i] - minPrice);
profits[i] = tmp;
minPrice = min(minPrice, prices[i]);
}

tmp = 0;
int maxPrice = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
tmp = max(tmp, maxPrice - prices[i]);
result = max(result, i > 0 ? tmp + profits[i - 1] : tmp);
maxPrice = max(maxPrice, prices[i]);
}

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