0714. Best Time to Buy and Sell Stock with Transaction Fee
Medium | Array + DP | 688 ms (75.06%), 21.1 MB (99.14%)
Input: prices = [1,3,2,8,4,9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
- Buying at prices[0] = 1
- Selling at prices[3] = 8
- Buying at prices[4] = 4
- Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
# (base case)
if len(prices) == 0 or len(prices) == 1: return 0
# ==================================================
# Array + Dynamic Programming (FSM) =
# ==================================================
# time : O(n)
# space : O(1)
hold, noHold = float('-inf'), 0
for price in prices:
preHold, preNoHold = hold, noHold
hold = max(preHold, preNoHold - price)
noHold = max(preNoHold, preHold + price - fee)
return noHoldclass Solution {
/**
* @time : O(n)
* @space : O(1)
public int maxProfit(int[] prices, int fee) {
/* base case */
if(prices.length == 1) return 0;
int hold = -prices[0], noHold = 0;
for(int i=1 ; i<prices.length ; i++) {
int preHold = hold, preNoHold = noHold;
hold = Math.max(preHold, preNoHold - prices[i]);
noHold = Math.max(preNoHold, preHold + prices[i] - fee);
}
return noHold;
}
}Last updated