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.