medium

Best Time to Buy and Sell Stock II

Maximize profit from a stock by buying and selling as many times as you like.

1. Define the problem

Best Time to Buy and Sell Stock II

You are given an integer array prices where pricesi is the price of a stock on day i. You may buy and sell as many times as you like, but must sell before buying again. Return the maximum profit you can achieve. Use a greedy single pass: whenever the price rises from one day to the next, bank that gain immediately, as if you bought the day before and sold today.

Constraints

  • 1 ≤ prices.length ≤ 3 × 104
  • 0 ≤ pricesi ≤ 104

Example

Inputprices = [7, 1, 5, 3, 6, 4]
Output7

Explanation Buy on day 1 (price 1), sell on day 2 (price 5), profit 4. Buy on day 3 (price 3), sell on day 4 (price 6), profit 3. Total 7.

2. Visualize the solution

Bank every day-over-day price increase

Bank every day-over-day price increase
Statusprofit=0

Day 1 price (1) is lower than day 0 (7) — nothing to capture.

What happens in this step

i = 1: prices[1] = 1, prices[0] = 7

1 < 7, so the price dropped. Nothing is captured — profit stays 0.
Step 1 of 5

Steps to visualize

  1. Compare each day to the day before it.
  2. If the price rose, add the difference to the running profit.
  3. If the price dropped or stayed the same, there is nothing to capture.
  4. The sum of every positive difference equals the maximum achievable profit.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Bank every day-over-day price increase
Statusprofit=0

Day 1 price (1) is lower than day 0 (7) — nothing to capture.

What happens in this step

i = 1: prices[1] = 1, prices[0] = 7

1 < 7, so the price dropped. Nothing is captured — profit stays 0.
Step 1 of 5
4. Solution

Solution

solution.tsTypeScript
function maxProfit(prices) {
  let profit = 0;

  for (let i = 1; i < prices.length; i++) {
    if (prices[i] > prices[i - 1]) {
      profit += prices[i] - prices[i - 1];
    }
  }

  return profit;
}
Time
O(n)
Space
O(1)
5. Test cases

Test cases

InputExpectedCovers
prices = [7, 1, 5, 3, 6, 4]7example from the docstring
prices = [1, 2, 3, 4, 5]4prices rise every day, capture every increase
prices = [7, 6, 4, 3, 1]0prices only fall, no profit possible
prices = [5]0smallest valid input, a single day with no trade possible
prices = [1, 5]4boundary case, one profitable trade
prices = [5, 1]0boundary case, price drops so no trade is worth making
prices = [3, 3, 3]0price never changes, nothing to capture