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.