Best Time to Buy and Sell Stock II

Medium#122every rise

You get the price of a share for each day. You may buy and sell as many times as you like, but hold at most one share at a time; selling and buying again on the same day is allowed. Find the largest total profit. Our example: [5, 2, 4, 7, 6, 3, 8] — the answer is 10: buy at 2 and sell at 7, then buy at 3 and sell at 8.

input
prices: a stock's price on each day. Each day you may buy one share, sell the one you hold, or both; you hold at most one share at a time.
returns
The largest total profit; 0 if no trade makes money.
constraints
  • 1 ≤ prices.length ≤ 5000
  • 0 ≤ prices[i] ≤ 10⁴
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} prices
 * @return {number}
 */
function maxProfit(prices) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more greedy problems

Pattern “Greedy” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.