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 INPUT Stock Prices Over Days 7 6 5 3 1 D0 D1 D2 D3 D4 D5 Buy Sell prices[] array: 7 1 5 3 6 4 [0] [1] [2] [3] [4] [5] ALGORITHM STEPS Greedy Approach 1 Initialize profit = 0 Track total gains 2 Loop through prices Compare adjacent days 3 Add positive diffs If p[i] > p[i-1], add diff 4 Return total profit Sum of all gains Profit Calculations: Day 1-2: 5-1 = +4 OK Day 2-3: 3-5 = -2 skip Day 3-4: 6-3 = +3 OK Day 4-5: 4-6 = -2 skip Total: 4 + 3 = 7 FINAL RESULT Optimal Trading Strategy Transaction 1 BUY Day 1: $1 SELL Day 2: $5 Profit: +$4 Transaction 2 BUY Day 3: $3 SELL Day 4: $6 Profit: +$3 Maximum Profit $7 Output: 7 Key Insight: The greedy approach captures EVERY upward price movement. Instead of trying to find optimal buy/sell pairs, we simply add all positive differences between consecutive days. Time: O(n), Space: O(1). Multiple small gains equal the same profit as waiting for peaks! TutorialsPoint - Best Time to Buy and Sell Stock II | Greedy Approach
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