Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 121 · State Machine / Stocks

Best Time to Buy and Sell Stock

LeetCode 121 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

profit(i) = price[i] − min(prices[0..i]).

సులభంArrayDynamic Programming

నేను Best Time to Buy and Sell Stock (LeetCode 121) ను ఇలా పరిష్కరించాను — State Machine / Stocks ప్యాటర్న్‌లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

If you sell on day i, the best buy day is simply the cheapest price before it. So walk forward remembering the minimum price so far and ask, every day, how much you'd make selling today.

Approach

  1. 1

    min_buy tracks the lowest price seen so far.

  2. 2

    For each price, update min_buy first, then compare price − min_buy against the best profit.

  3. 3

    If prices only fall, the best profit stays 0 (don't trade).

నేను ఎలా పరిష్కరించాను

One pass, running minimumPythonO(n) time · O(1) space
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_buy = prices[0]
        max_profit= 0
        for price in prices:
            min_buy = min(price,min_buy)
            max_profit = max(max_profit,price-min_buy)
        return max_profit
స్టెప్-త్రూ లోడ్ అవుతోంది…

Best Time to Buy and Sell Stock — తరచూ అడిగే ప్రశ్నలు

Best Time to Buy and Sell Stock వెనుక ఉన్న intuition ఏమిటి?

If you sell on day i, the best buy day is simply the cheapest price before it. So walk forward remembering the minimum price so far and ask, every day, how much you'd make selling today.

Best Time to Buy and Sell Stock (LeetCode 121) ను ఎలా పరిష్కరించాలి?

1. min_buy tracks the lowest price seen so far. 2. For each price, update min_buy first, then compare price − min_buy against the best profit. 3. If prices only fall, the best profit stays 0 (don't trade).

Best Time to Buy and Sell Stock యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(1). (Accepted approach: One pass, running minimum.)

Best Time to Buy and Sell Stock లో సాధారణ పొరపాట్లు ఏమిటి?

You must buy before you sell — max(prices) − min(prices) ignores order.