Best Time to Buy and Sell Stock with Transaction Fee
LeetCode 714 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Subtract the fee once per transaction, on the sell edge.
నేను Best Time to Buy and Sell Stock with Transaction Fee (LeetCode 714) ను ఇలా పరిష్కరించాను — State Machine / Stocks ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Same two-mode state machine as the other stock problems — free to buy, or holding. The only twist is that every completed trade costs a fee, so charge it at the moment you sell.
Approach
- 1
State: (index, can_buy) → best profit from this day onward.
- 2
Buy mode: max(buy today, wait).
- 3
Hold mode: max(sell today − fee, wait).
- 4
Memoise with lru_cache; the answer is dfs(0, True).
నేను ఎలా పరిష్కరించాను
State machine + memoPythonO(n) time · O(n) space
#2n > n, SC - 2n>n
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
@lru_cache(maxsize=None)
def dfs(index,can_buy):
if index>=n:
return 0
if can_buy:
buy = -prices[index]+dfs(index+1,False)
hold= dfs(index+1,True)
return max(buy,hold)
else:
sell = prices[index]+dfs(index+1,True)-fee
hold= dfs(index+1,False)
return max(sell,hold)
return dfs(0,True)Best Time to Buy and Sell Stock with Transaction Fee — తరచూ అడిగే ప్రశ్నలు
Best Time to Buy and Sell Stock with Transaction Fee వెనుక ఉన్న intuition ఏమిటి?
Same two-mode state machine as the other stock problems — free to buy, or holding. The only twist is that every completed trade costs a fee, so charge it at the moment you sell.
Best Time to Buy and Sell Stock with Transaction Fee (LeetCode 714) ను ఎలా పరిష్కరించాలి?
1. State: (index, can_buy) → best profit from this day onward. 2. Buy mode: max(buy today, wait). 3. Hold mode: max(sell today − fee, wait). 4. Memoise with lru_cache; the answer is dfs(0, True).
Best Time to Buy and Sell Stock with Transaction Fee యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(n). (Accepted approach: State machine + memo.)
Best Time to Buy and Sell Stock with Transaction Fee లో సాధారణ పొరపాట్లు ఏమిటి?
Charging the fee on both buy and sell double-counts it. Recursion depth grows with n — iterative two-variable DP avoids that for very long inputs.