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.