Tensorum
YouTubeশেখা শুরু করুন
LeetCode 123 · State Machine / Stocks

Best Time to Buy and Sell Stock III

LeetCode 123 · কঠিন · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Effective second buy = price − best first profit.

কঠিনArrayDynamic Programming

আমি Best Time to Buy and Sell Stock III (LeetCode 123) এভাবে সমাধান করেছি — State Machine / Stocks প্যাটার্নের একটি কঠিন প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।

নিচের বিবরণ ইংরেজিতে।

Intuition

Run the one-transaction trick twice, chained. The first trade tracks its cheapest buy and best profit as usual. For the second trade, the profit already banked from the first makes the second buy effectively cheaper: its cost is price − profit₁.

Approach

  1. 1

    min_buy_t1 / max_profit_1: the classic single-trade scan.

  2. 2

    min_buy_t2 = min(min_buy_t2, price − max_profit_1): reinvest the first profit.

  3. 3

    max_profit_2 = max(max_profit_2, price − min_buy_t2): best total after two trades.

  4. 4

    Update all four in one pass; max_profit_2 is the answer (it also covers using only one trade).

আমি কীভাবে সমাধান করেছি

Four-variable state machinePythonO(n) time · O(1) space
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_buy_t1 = float("inf")
        min_buy_t2 = float("inf")
        max_profit_1=0
        max_profit_2=0
        for price in prices:
            min_buy_t1=min(min_buy_t1,price)
            max_profit_1 = max(max_profit_1,price - min_buy_t1)
            min_buy_t2=min(min_buy_t2,price-max_profit_1)
            max_profit_2 =max(max_profit_2,price - min_buy_t2) 
        return max_profit_2
স্টেপ-থ্রু লোড হচ্ছে…

Best Time to Buy and Sell Stock III — সাধারণ প্রশ্ন

Best Time to Buy and Sell Stock III-এর পেছনে intuition কী?

Run the one-transaction trick twice, chained. The first trade tracks its cheapest buy and best profit as usual. For the second trade, the profit already banked from the first makes the second buy effectively cheaper: its cost is price − profit₁.

Best Time to Buy and Sell Stock III (LeetCode 123) কীভাবে সমাধান করবেন?

1. min_buy_t1 / max_profit_1: the classic single-trade scan. 2. min_buy_t2 = min(min_buy_t2, price − max_profit_1): reinvest the first profit. 3. max_profit_2 = max(max_profit_2, price − min_buy_t2): best total after two trades. 4. Update all four in one pass; max_profit_2 is the answer (it also covers using only one trade).

Best Time to Buy and Sell Stock III-এর time আর space complexity কত?

Time: O(n)। Space: O(1)। (Accepted approach: Four-variable state machine।)

Best Time to Buy and Sell Stock III-এ সাধারণ ভুলগুলো কী?

Splitting the array at every point and running two separate scans works but is easier to get wrong. Order of updates within a day is fine here because same-day buy/sell gives zero extra profit.