sagelearnai

Best Time to Buy and Sell Stock II

Difficulty: Medium · Pattern: Greedy · LeetCode #122

You may buy and sell as many times as you like, holding at most one share at a time (you may sell and buy again on the same day). Return the maximum profit.

Examples

text
[7,1,5,3,6,4]  →  7    (buy 1 sell 5, buy 3 sell 6)
[1,2,3,4,5]    →  4
[7,6,4,3,1]    →  0

Hints

  1. Any long rise from day i to day j can be split into consecutive one-day rises with the same total.

Approach

Sum max(0, prices[i] − prices[i−1]) over all days. Each positive step is a one-day trade, and a multi-day upswing is just the sum of its daily steps (it telescopes). Skipping down days loses nothing, so this captures every possible gain.

DP view: hold and cash states, with cash = max(cash, hold + p) and hold = max(hold, cash − p). That form generalizes to the cooldown and fee variants.

Complexity

Time: O(n). Space: O(1).

Python solution
def maxProfit(prices):
    return sum(max(0, b - a) for a, b in zip(prices, prices[1:]))
JavaScript solution
function maxProfit(prices) {
  let p = 0;
  for (let i = 1; i < prices.length; i++) if (prices[i] > prices[i - 1]) p += prices[i] - prices[i - 1];
  return p;
}