Best Time to Buy and Sell Stock II
LeetCode 122 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Sum of all positive deltas = best profit with unlimited trades.
ನಾನು Best Time to Buy and Sell Stock II (LeetCode 122) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Jump / Reachability ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
With unlimited transactions, any rise from one day to the next is money you can collect. A long climb from 1 to 5 is the same as collecting every small daily step on the way up, so just add up every positive day-to-day difference.
Approach
- 1
Compare each day with the day before.
- 2
If today is higher, add the gain to the profit.
- 3
Ignore falling days — you'd simply not hold stock across them.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Greedy deltasPythonO(n) time · O(1) space
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1,len(prices)):
if prices[i]>prices[i-1]:
profit+=prices[i]-prices[i-1]
return profitBest Time to Buy and Sell Stock II — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Best Time to Buy and Sell Stock II ಹಿಂದಿನ intuition ಏನು?
With unlimited transactions, any rise from one day to the next is money you can collect. A long climb from 1 to 5 is the same as collecting every small daily step on the way up, so just add up every positive day-to-day difference.
Best Time to Buy and Sell Stock II (LeetCode 122) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Compare each day with the day before. 2. If today is higher, add the gain to the profit. 3. Ignore falling days — you'd simply not hold stock across them.
Best Time to Buy and Sell Stock II ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(1). (Accepted approach: Greedy deltas.)
Best Time to Buy and Sell Stock II ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
This greedy only works because transactions are unlimited and free — fees or cooldowns need the DP versions.