Skip to main content

Stock Profit With Many Trades

MediumArraysGreedy223 tests

You get an array prices. prices[i] is the price of one share of a stock on day i.

You may buy and sell as many times as you want. The only rule: you can hold at most one share at a time. So you must sell the share you hold before you buy again. You may sell and buy again on the same day.

Return the largest total profit you can make. If no trade makes money, return 0.

Hint

Look at each pair of neighbouring days. When does it help you to own the share from one day to the next?

Examples

Example 1

Input:
[3,8,2,6,9]
Output:
12

Buy at 3 and sell at 8 (profit 5). Then buy at 2 and sell at 9 (profit 7). The total is 12.

Example 2

Input:
[9,7,7,4]
Output:
0

The price never goes up, so any trade loses money or makes nothing. Do not trade.

Example 3

Input:
[2,3,4,5]
Output:
3

Buy at 2 and sell at 5. Selling and buying again every day gives the same total: 1 + 1 + 1 = 3.

Constraints

  • 1 <= prices.length <= 15
  • 0 <= prices[i] <= 1000

Run checks your code against the 3 examples. Submit checks it against all 223 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.