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]
之后,依次枚举分割点,求解两个子问题的和即可。
代码:
最直观的想法就是划分成两个子问题,每个子问题变成了:求在某个范围内交易一次的最大利润
在只能交易一次的情况下,如何求一段时间内的最大利润?其实就是找股价最低的一天买进,然后在股价最高的一天卖出,当然,卖股票要在买股票之后。
用迭代法求这个问题非常容易,令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; }
相关文章推荐
- [LeetCode]123 Best Time to Buy and Sell Stock III
- LeerCode 123 Best Time to Buy and Sell Stock III之O(n)解法
- 123 Best time to buy and sell stock iii
- 123. Best Time to Buy and Sell Stock III
- leetcode || 123、Best Time to Buy and Sell Stock III
- leetcode-123 Best Time to Buy and Sell Stock III
- LeerCode 123 Best Time to Buy and Sell Stock III之O(n)解法
- Java for LeetCode 123 Best Time to Buy and Sell Stock III【HARD】
- Leetcode 123 Best Time to Buy and Sell Stock III 至多两次买卖股票最大收益
- LeetCode 123 Best Time to Buy and Sell StockIII
- LeetCode123:Best Time to Buy and Sell Stock III
- Leetcode_123_Best Time to Buy and Sell Stock III
- [leetcode] 123.Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III [123]
- leetcode[123]Best Time to Buy and Sell Stock III
- Lettcode_123_Best Time to Buy and Sell Stock III
- LeetCode(123) Best Time to Buy and Sell Stock III (Java)
- [LeetCode 123] - 买入与卖出股票的最佳时机III(Best Time to Buy and Sell Stock III)
- leetcode解题报告:123 Best Time to Buy and Sell Stock III
- leetcode 123 Best Time to Buy and Sell Stock III