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.