Best Time to Buy and Sell Stock III
LeetCode 123 · कठीण · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Effective second buy = price − best first profit.
मी 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
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).
मी कसा सोडवला
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_2Best 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.