Best Time to Buy and Sell Stock IV
LeetCode 188 · கடினம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
min_buy[i] = min(min_buy[i], price − max_profit[i-1]); max_profit[i] = max(max_profit[i], price − min_buy[i]).
நான் Best Time to Buy and Sell Stock IV (LeetCode 188) ஐ இப்படித் தீர்த்தேன் — State Machine / Stocks பேட்டர்னின் ஒரு கடினம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Generalise the two-transaction chain to k. Transaction i's effective buy price is the stock price minus the profit already locked in by transaction i-1, so keep an array of k effective buys and k best profits and update them all on every day.
Approach
- 1
Arrays of size k+1; index 0 is the 'no transaction yet' sentinel with profit 0.
- 2
For each price, for i = 1..k: update the effective buy for trade i, then its best profit.
- 3
max_profit[k] holds the best total using at most k trades.
நான் எப்படித் தீர்த்தேன்
k-state machinePythonO(n·k) time · O(k) space
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
min_buy = [float("inf")]*(k+1)
max_profit = [0]*(k+1)
for price in prices:
for i in range(1,k+1):
min_buy[i]=min(min_buy[i],price-max_profit[i-1])
max_profit[i]=max(max_profit[i],price-min_buy[i])
return max_profit[k]
Best Time to Buy and Sell Stock IV — அடிக்கடி கேட்கப்படும் கேள்விகள்
Best Time to Buy and Sell Stock IV பின்னாலுள்ள intuition என்ன?
Generalise the two-transaction chain to k. Transaction i's effective buy price is the stock price minus the profit already locked in by transaction i-1, so keep an array of k effective buys and k best profits and update them all on every day.
Best Time to Buy and Sell Stock IV (LeetCode 188) ஐ எப்படித் தீர்ப்பது?
1. Arrays of size k+1; index 0 is the 'no transaction yet' sentinel with profit 0. 2. For each price, for i = 1..k: update the effective buy for trade i, then its best profit. 3. max_profit[k] holds the best total using at most k trades.
Best Time to Buy and Sell Stock IV இன் time மற்றும் space complexity என்ன?
Time: O(n · k). Space: O(k). (Accepted approach: k-state machine.)
Best Time to Buy and Sell Stock IV இல் பொதுவான தவறுகள் என்ன?
Note the argument order: k comes before prices. When k ≥ n/2 the problem becomes unlimited trades — the same code still works, just slower.