Best Time to Buy and Sell Stock II

Medium

prices[i] is the price of a stock 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.

Return the maximum profit you can make.

Example 1

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

Why

Buy at 1, sell at 5, buy at 3, sell at 6.

Example 2

maxProfitII()
Input
prices = [1,2,3,4,5]
Output
4
Constraints
1 <= prices.length <= 3 * 10^4
0 <= prices[i] <= 10^4

Topics

ArraysGreedyDynamic Programming

Implement maxProfitII in the editor and return the answer — printing it is never graded.