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.