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.