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 sell and buy the stock multiple times on the same day, ensuring you never hold more than one share of the stock.
Find and return the maximum profit you can achieve.
Input & Output
Example 1 — Multiple Profitable Trades
$
Input:
prices = [7,1,5,3,6,4]
›
Output:
7
💡 Note:
Buy on day 2 (price = 1), sell on day 3 (price = 5), profit = 4. Buy on day 4 (price = 3), sell on day 5 (price = 6), profit = 3. Total profit = 4 + 3 = 7.
Example 2 — Declining Prices
$
Input:
prices = [7,6,4,3,1]
›
Output:
0
💡 Note:
Prices only decrease, so no profitable trades are possible. Maximum profit is 0.
Example 3 — Single Day
$
Input:
prices = [1]
›
Output:
0
💡 Note:
Cannot make any trades with only one day of prices.
Constraints
- 1 ≤ prices.length ≤ 3 × 104
- 0 ≤ prices[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of stock prices over consecutive days
2
Process
Identify all profitable buy-sell opportunities
3
Output
Maximum total profit from all transactions
Key Takeaway
🎯 Key Insight: Maximum profit is the sum of all profitable day-to-day price increases
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code