Algorithm

Best Time to Buy and Sell Stock II Algorithm

This is a twist on the classic stock problem. You can buy and sell as many times as you want — but you can only hold one share at a time.

27 Mar 2024

Best Time to Buy and Sell Stock II Algorithm

This is a twist on the classic stock problem. You can buy and sell as many times as you want — but you can only hold one share at a time.

The Problem

Given an array prices where prices[i] is the stock price on day i, find the maximum profit. You can make multiple transactions.

Input: prices = [7,1,5,3,6,4]
Output: 7
Buy at 1, sell at 5 (profit 4). Buy at 3, sell at 6 (profit 3). Total: 7.

The Insight

Forget trying to find the perfect buy-sell pairs. Just capture every upswing.

If tomorrow's price is higher than today's, that's profit. Add it up. You're collecting every single price increase across the entire array.

It sounds too simple to work. But it does. Any multi-day profit can be decomposed into a chain of consecutive-day gains.

The Code

Javascript
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;
}

console.log(maxProfit([7, 1, 5, 3, 6, 4])); // 7
console.log(maxProfit([1, 2, 3, 4, 5]));    // 4
console.log(maxProfit([7, 6, 4, 3, 1]));    // 0

Complexity

  • Time: O(n) — single pass through the array.
  • Space: O(1) — just one variable.

Why This Works

Consider prices [1, 2, 3]. Buying at 1 and selling at 3 gives profit 2. But so does buying at 1, selling at 2 (profit 1), then buying at 2, selling at 3 (profit 1). Same result.

By summing every positive difference, you automatically capture every profitable window. No need to track buy/sell points explicitly.

The Trade-off

This greedy approach is optimal for unlimited transactions. But add constraints — like a cooldown period, a transaction fee, or a max number of trades — and you need dynamic programming instead.