Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 122 · Jump / Reachability

Best Time to Buy and Sell Stock II

LeetCode 122 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Sum of all positive deltas = best profit with unlimited trades.

మధ్యస్థంArrayDynamic ProgrammingGreedy
LeetCode లో తెరవండి ↗

నేను 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. 1

    Compare each day with the day before.

  2. 2

    If today is higher, add the gain to the profit.

  3. 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 profit
స్టెప్-త్రూ లోడ్ అవుతోంది…

Best 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.