Best Time to Buy and Sell Stock
LeetCode 121 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
profit(i) = price[i] − min(prices[0..i]).
मी 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
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).
मी कसा सोडवला
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_profitBest 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.