[LeetCode] [Python] [DP] Best Time to Buy and Sell Stock III
2014-10-29 22:32
351 查看
题目与一类似,唯一的不同就是这回可以有两次交易,但是两次交易不能同时存在,即:第一次交易结束之前(买入和卖出都操作即为结束一次交易)不能进行第二次的交易
第一道题目我在前面的博客中已经给出了,是一个O(n)的时间复杂度。
那么我们就来分析一下此题: 假设n = len(prices)
联系第一题我们不难得出这个结论:我们可以讲两次交易分开,那么我们就是要求max(0, f(0,i)+f(i,n-1)) 其中i属于[0,n-1]
我们可以发现f(0,i)实际上就是第一题的解法,那么对于f(i,n-1)呢。
实际上我们仔细观察不难发现其实这个问题是对称的,这里大家可以仔细思考下
时间复杂度O(n) 空间复杂度O(n)
第一道题目我在前面的博客中已经给出了,是一个O(n)的时间复杂度。
那么我们就来分析一下此题: 假设n = len(prices)
联系第一题我们不难得出这个结论:我们可以讲两次交易分开,那么我们就是要求max(0, f(0,i)+f(i,n-1)) 其中i属于[0,n-1]
我们可以发现f(0,i)实际上就是第一题的解法,那么对于f(i,n-1)呢。
实际上我们仔细观察不难发现其实这个问题是对称的,这里大家可以仔细思考下
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices) : n = len(prices) if n < 2 : return 0 f = {} mi = prices[0] got = 0 for i in range(0,n) : got = max(got,prices[i]-mi) f[(0,i)] = got mi = min(mi,prices[i]) i = n - 1 got = 0 ma = prices[i] while i >= 0 : got = max(got,ma-prices[i]) f[(i,n-1)] = got ma = max(ma,prices[i]) i -= 1 ma = 0 for i in range(0,n) : ma = max(ma, f[(0,i)] + f[(i,n-1)]) return ma
时间复杂度O(n) 空间复杂度O(n)
相关文章推荐
- [LeetCode]题解(python):123-Best Time to Buy and Sell Stock III
- [leetcode][DP] Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III Leetcode Python
- [leetcode][DP] Best Time to Buy and Sell Stock III
- leetcode123. [DP]Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III @ Python
- leetcode_[python/C++]_121/122/123/188.Best Time to Buy and Sell Stock I/II/III/IV
- [Leetcode][python]Best Time to Buy and Sell Stock I/II/III
- [LeetCode] [Python] [DP] Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock III(dp)
- 【Leetcode】Best Time to Buy and Sell Stock III (DP)
- [leetcode]Best Time to Buy and Sell Stock III @ Python
- Leetcode::Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III
- 【LeetCode with Python】 Best Time to Buy and Sell Stock II
- [Leetcode]Best Time to Buy and Sell Stock III
- [LeetCode 123] - 买入与卖出股票的最佳时机III(Best Time to Buy and Sell Stock III)
- LeetCode Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III