Best Time to Buy and Sell Stock II - Problem
Imagine you're a day trader with perfect knowledge of future stock prices! You have an array prices where prices[i] represents the stock price on day i.
Your goal is to maximize profit by buying and selling strategically with these rules:
- ๐น You can hold at most one share at any time
- ๐น You can buy and sell multiple times
- ๐น You can even buy and sell on the same day
- ๐น You must buy before you sell
Return the maximum profit you can achieve.
Example: If prices = [7,1,5,3,6,4], you could:
- Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 4
- Buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 3
- Total profit = 7
Input & Output
example_1.py โ Basic Case
$
Input:
prices = [7,1,5,3,6,4]
โบ
Output:
7
๐ก Note:
Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 3. Total profit = 7.
example_2.py โ Increasing Prices
$
Input:
prices = [1,2,3,4,5]
โบ
Output:
4
๐ก Note:
Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 4. Alternatively, you can buy and sell every day for the same total profit.
example_3.py โ Decreasing Prices
$
Input:
prices = [7,6,4,3,1]
โบ
Output:
0
๐ก Note:
Since prices are always decreasing, no profit can be made. The best strategy is to never buy.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Price Increases
Scan through prices and find every day where price > previous day's price
2
Capture Each Profit
For each price increase, add the difference to our total profit
3
Sum All Gains
The sum of all positive price differences gives us maximum profit
Key Takeaway
๐ฏ Key Insight: Since we can perform unlimited transactions, the optimal strategy is to capture every single profitable price increase. This greedy approach guarantees maximum profit!
Time & Space Complexity
Time Complexity
O(n)
Single pass through the price array
โ Linear Growth
Space Complexity
O(1)
Only using a constant amount of extra space
โ Linear Space
Constraints
- 1 โค prices.length โค 3 ร 104
- 0 โค prices[i] โค 104
- You can perform multiple transactions
- You can only hold at most one share at any time
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code