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.