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.