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

मी 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.