給定一個整數數組 prices,其中 prices[i]表示第 i 天的股票價格 ;整數 fee 代表了交易股票的手續費用。
你可以無限次地完成交易,但是你每筆交易都需要付手續費。如果你已經購買了一個股票,在賣出它之前你就不能再繼續購買股票了。
返回獲得利潤的最大值。
注意:這裏的一筆交易指買入持有並賣出股票的整個過程,每筆交易你只需要爲支付一次手續費。
示例 1:
輸入:prices = [1, 3, 2, 8, 4, 9], fee = 2
輸出:8
解釋:能夠達到的最大利潤:
在此處買入 prices[0] = 1
在此處賣出 prices[3] = 8
在此處買入 prices[4] = 4
在此處賣出 prices[5] = 9
總利潤: ((8 - 1) - 2) + ((9 - 4) - 2) = 8
示例 2:
輸入:prices = [1,3,7,5,10,3], fee = 3
輸出:6
提示:
1 <= prices.length <= 5 * 104
1 <= prices[i] < 5 * 104
0 <= fee < 5 * 104
【分析】
class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: n = len(prices) sell, buy = 0, -prices[0] for i in range(1, n): sell, buy = max(sell, buy + prices[i] - fee), max(buy, sell - prices[i]) return sell