Skip to problem
←

Best Time to Buy and Sell Stock II

Medium 0 attempts

You're given an integer array prices, where prices[i] is the stock's price on day i. You're free to buy and sell as many times as you like, on any days, but you can never hold more than one share at once (so you must sell before buying again). Determine the maximum total profit obtainable.

Function contract

Implement maxProfit(prices), where prices[i] is the price on day i.

Output: The maximum total profit from any number of buy-then-sell transactions while holding at most one share at a time.

Example 1

Input
prices = [7,1,5,3,6,4]
Output
7

Explanation: Buy at 1 and sell at 5, then buy at 3 and sell at 6: 4 + 3 = 7.

Example 2

Input
prices = [7,6,4,3,1]
Output
0
Constraints
  • 1 <= prices.length <= 3 * 10^4
  • 0 <= prices[i] <= 10^4
Topics

Iterate through prices and add every positive difference between consecutive days to the total profit. This captures every upward movement.

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

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript