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.