MEDIUM Dynamic Programming / Greedy
122. Best Time to Buy and Sell Stock II
📖 Problem
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
- •Array DP table updates
- •State transition thinking
- •Base case initialization
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply Dynamic Programming reasoning pattern
- •Apply Greedy reasoning pattern
💡 Approach
- → Can buy and sell on same day (unlimited transactions)
- → Add profit when price increases from previous day
- → Time: O(n), Space: O(1)
🛠️ Hints & Pitfalls
Hints
- •Can buy and sell on same day (unlimited transactions)
- •Add profit when price increases from previous day
- •Time: O(n), Space: O(1)
🧪 Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
maxProfit([7,1,5,3,6,4]); Expected:
7 Test Case 2
Not run Input:
maxProfit([1,2,3,4,5]); Expected:
4 Test Case 3
Not run Input:
maxProfit([7,6,4,3,1]); Expected:
0 📝 Code Editor
📤 Output