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.