LeetCode刷题实战123:买卖股票的最佳时机 III
共 1671字,需浏览 4分钟
·
2020-12-16 21:15
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
题意
解题
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
len_prices = len(prices)
buy1, sell1, buy2, sell2 = -prices[0], 0, -prices[0], 0
for i in range(1, len_prices):
buy1 = max(buy1, -prices[i])
sell1 = max(sell1, buy1 + prices[i])
buy2 = max(buy2, sell1 - prices[i])
sell2 = max(sell2, buy2 + prices[i])
return sell2