Best Time to Buy and Sell Stock II
LeetCode 122 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Sum of all positive deltas = best profit with unlimited trades.
நான் Best Time to Buy and Sell Stock II (LeetCode 122) ஐ இப்படித் தீர்த்தேன் — Jump / Reachability பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
With unlimited transactions, any rise from one day to the next is money you can collect. A long climb from 1 to 5 is the same as collecting every small daily step on the way up, so just add up every positive day-to-day difference.
Approach
- 1
Compare each day with the day before.
- 2
If today is higher, add the gain to the profit.
- 3
Ignore falling days — you'd simply not hold stock across them.
நான் எப்படித் தீர்த்தேன்
Greedy deltasPythonO(n) time · O(1) space
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1,len(prices)):
if prices[i]>prices[i-1]:
profit+=prices[i]-prices[i-1]
return profitBest Time to Buy and Sell Stock II — அடிக்கடி கேட்கப்படும் கேள்விகள்
Best Time to Buy and Sell Stock II பின்னாலுள்ள intuition என்ன?
With unlimited transactions, any rise from one day to the next is money you can collect. A long climb from 1 to 5 is the same as collecting every small daily step on the way up, so just add up every positive day-to-day difference.
Best Time to Buy and Sell Stock II (LeetCode 122) ஐ எப்படித் தீர்ப்பது?
1. Compare each day with the day before. 2. If today is higher, add the gain to the profit. 3. Ignore falling days — you'd simply not hold stock across them.
Best Time to Buy and Sell Stock II இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Greedy deltas.)
Best Time to Buy and Sell Stock II இல் பொதுவான தவறுகள் என்ன?
This greedy only works because transactions are unlimited and free — fees or cooldowns need the DP versions.