LeetCode解题之Best Time to Buy and Sell Stock III
原题
给定每天的股票价格,如果最多允许两次交易,但手中最多只能持有一支股票,在再次买入的时候必须将之前的股票卖出,求能获取的最大利润。
注意点:
- 无
例子:
输入: prices = [2, 4, 6, 1, 3, 8, 3]
输出: 11([2,6]、[1,8]是两次进行买入卖出的时机)
解题思路
因为最多只能进行两次交易,所以可以将时间一划为二,分别找这两段时间内进行一次(也可能不进行交易)所能获得的最大利润(方法参见 Best Time to Buy and Sell Stock),将两者相加就是在这种划分情况下最多进行两次交易所能获取的最大利润。遍历所有的划分可能,就能找出最终的最大利润。如果每次都将时间段直接调用Best Time to Buy and Sell Stock的方法,复杂的用例会超时。我们可以先从前往后遍历,并缓存最多进行一次交易所能获取的最大利润;再从后往前遍历计算最多进行一次交易所能获取的最大利润,与对应的缓存相加就是在一次划分下的最大利润。
AC源码
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
total_max_profit = 0
n = len(prices)
first_profits = [0] * n
min_price = float('inf')
for i in range(n):
min_price = min(min_price, prices[i])
total_max_profit = max(total_max_profit, prices[i] - min_price)
first_profits[i] = total_max_profit
max_profit = 0
max_price = float('-inf')
for i in range(n - 1, 0, -1):
max_price = max(max_price, prices[i])
max_profit = max(max_profit, max_price - prices[i])
total_max_profit = max(total_max_profit, max_profit + first_profits[i - 1])
return total_max_profit
if __name__ == "__main__":
assert Solution().maxProfit([2, 4, 6, 1, 3, 8, 3]) == 11
assert Solution().maxProfit([1, 2]) == 1
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。