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.