dsa · easy

Best Time to Buy and Sell Stock II

You are given prices where prices[i] is the price of one share on day i. You may buy and sell as many times as you like, but you may hold at most one share at a time and must sell before buying again. Return the maximum total profit you can lock in.

Arguments

Example

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

Buy at 1 on day 2, sell at 5 on day 3 (+4); buy at 3 on day 4, sell at 6 on day 5 (+3). Total 7.

prices = [7,6,4,3,1] → prices only fall, so every trade loses money; make none → 0.

Constraints

1 <= prices.length <= 3 * 10^4 0 <= prices[i] <= 10^4 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
[7,1,5,3,6,4]

Expected:
7

Example 2

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

Expected:
4

Example 3

Input:
[7,6,4,3,1]

Expected:
0

Open in the Dojo editor