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
Best Time to Buy and Sell Stock II: Multiple Transactions715364Day 0Day 1Day 2Day 3Day 4Day 5BSBSBuy at 1Sell at 5Buy at 3Sell at 6Profit: (5-1) + (6-3) = 4 + 3 = 7Maximum Profit: 7
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
Asked in
Amazon 85 Google 70 Microsoft 65 Apple 60
330.0K Views
High Frequency
~15 min Avg. Time
8.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen