Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 714 · State Machine / Stocks

Best Time to Buy and Sell Stock with Transaction Fee

LeetCode 714 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Subtract the fee once per transaction, on the sell edge.

நடுத்தரம்ArrayDynamic ProgrammingGreedy
LeetCode இல் திற ↗

நான் 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. 1

    State: (index, can_buy) → best profit from this day onward.

  2. 2

    Buy mode: max(buy today, wait).

  3. 3

    Hold mode: max(sell today − fee, wait).

  4. 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.