[Leetcode]123.买卖股票的最佳时机3
2018-12-30 23:57
507 查看
[原题链接][https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/]
分析:动态规划+二分法。以
第i天为分界线,计算第i天之前进行
一次交易的最大收益
left[i],和第i天之后进行
一次交易的最大收益
right[i],最后遍历一遍找到
max{left[i] + right[i]} (0≤i≤n-1),就是最大收益。第i天之前和第i天之后进行一次的最大收益求法如最简单的股票买卖问题。
再求解前先看看最简单的求
一次交易的最大收益解法
/*用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。 如果只允许进行一次交易,也就是说只允许买一支股票并卖掉,求最大的收益。 题解:动态规划法。从前向后遍历数组,记录当前出现过的最低价格,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益,整个遍历过程中,出现过的最大收益就是所求。*/ int maxProfit(const int prices[],const int len){ if(len<2) return 0; int maxProfit = 0; int curMin = prices[0]; /*发现只进行了一次遍历*/ for (int i = 1; i < len;i++){ curMin = min(curMin, prices[i]); maxProfit = max(maxProfit, prices[i] - curMin); /*每次遍历后的maxProfix就是 从prices[0]开始到prices[i]的最大收益*/ } return maxProfit; }
利用上述最简单情况的求一次交易的最大收益方法,顺序遍历一遍把每个阶段的maxProfit保留到
left[i],逆序遍历一遍并把每个阶段的maxProfit保留到
right[i]中。
上面代码只进行了一次遍历,验证了下面代码的
left[i]和
right[i]就是
第i天前一次交易最大收益和
第i天后一次交易最大收益
时间复杂度:O(n)
class Solution { public: int maxProfit(vector<int> &prices) { int s = prices.size(); if (s < 2) return 0; int preMaxvalue[s], postMaxvalue[s]; memset(preMaxvalue, 0, sizeof(preMaxvalue)); memset(postMaxvalue, 0, sizeof(postMaxvalue)); int curMin = prices[0]; for (int i = 1; i < s; i++) { curMin = min(curMin, prices[i]); preMaxvalue[i] = max(preMaxvalue[i - 1], prices[i] - curMin); } int curMax = prices[s - 1]; for (int i = s - 2; i >= 0; i--) { curMax = max(curMax, prices[i]); postMaxvalue[i] = max(postMaxvalue[i + 1], curMax - prices[i]); } int maxProfit = 0; for (int i = 0; i < s; i++) { maxProfit = max(maxProfit, preMaxvalue[i] + postMaxvalue[i]); } return maxProfit; } };
相关文章推荐
- LeetCode-123.买卖股票的最佳时机III(相关话题:动态规划)
- Leetcode 121. 买卖股票的最佳时机
- [Leetcode] Best time to buy and sell stock 买卖股票的最佳时机
- LeetCode 122. 买卖股票的最佳时机 II
- LeetCode - 122. 买卖股票的最佳时机 II
- Leetcode 买卖股票的最佳时机 II
- [Java语言] [Leetcode] Best Time to Buy and Sell Stock 买卖股票的最佳时机
- Leetcode121 Best Time to Buy and Sell Stock(买卖股票的最佳时机1)
- leetcode-买卖股票的最佳时机 II
- LeetCode 121. 买卖股票的最佳时机
- LeetCode 121. 买卖股票的最佳时机
- LeetCode-121.买卖股票的最佳时机(相关话题:动态规划)
- LeetCode 121 买卖股票的最佳时机 Python
- LeetCode 122. 买卖股票的最佳时机 II
- LeetCode-122.买卖股票的最佳时机II(相关话题:贪心算法)
- [Leetcode] Best time to buy and sell stock ii 买卖股票的最佳时机
- LeetCode 122 买卖股票的最佳时机2 Python
- LeetCode 123. 买卖股票的最佳时机 III
- LeetCode:买卖股票的最佳时机 II
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock