|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ |
| 3 | +
|
| 4 | +You are given an array prices where prices[i] is the price of a given stock on |
| 5 | +the ith day, and an integer fee representing a transaction fee. |
| 6 | +Find the maximum profit you can achieve. You may complete as many |
| 7 | +transactions as you like, but you need to pay the transaction fee for |
| 8 | +each transaction. |
| 9 | +Note: You may not engage in multiple transactions simultaneously |
| 10 | +(i.e., you must sell the stock before you buy again). |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +Input: prices = [1,3,2,8,4,9], fee = 2 |
| 14 | +Output: 8 |
| 15 | +Explanation: The maximum profit can be achieved by: |
| 16 | +- Buying at prices[0] = 1 |
| 17 | +- Selling at prices[3] = 8 |
| 18 | +- Buying at prices[4] = 4 |
| 19 | +- Selling at prices[5] = 9 |
| 20 | +The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. |
| 21 | +
|
| 22 | +Example 2: |
| 23 | +Input: prices = [1,3,7,5,10,3], fee = 3 |
| 24 | +Output: 6 |
| 25 | + |
| 26 | +Constraints: |
| 27 | +1 <= prices.length <= 5 * 104 |
| 28 | +1 <= prices[i] < 5 * 104 |
| 29 | +0 <= fee < 5 * 104 |
| 30 | +""" |
| 31 | +class Solution: |
| 32 | + def maxProfit(self, prices: List[int], fee: int) -> int: |
| 33 | + buy = -prices[0] |
| 34 | + sell = 0 |
| 35 | + |
| 36 | + for i in range(1, len(prices)): |
| 37 | + buy = max(buy, sell-prices[i]) |
| 38 | + sell = max(sell, buy + prices[i] - fee) |
| 39 | + |
| 40 | + return sell |
| 41 | + |
| 42 | +# Better variable names |
| 43 | +class Solution: |
| 44 | + def maxProfit(self, prices: List[int], fee: int) -> int: |
| 45 | + cash, hold = 0, -prices[0] |
| 46 | + |
| 47 | + for i in range(1, len(prices)): |
| 48 | + cash = max(cash, hold + prices[i] - fee) |
| 49 | + hold = max(hold, cash - prices[i]) |
| 50 | + |
| 51 | + return cash |
0 commit comments