Best Time to Buy and Sell Stock II
Problem statement
prices[i] is the price of one share on day i. Starting with no shares, choose purchases and sales to maximize your total realized profit.
You may complete any number of transactions, but you may hold at most one share at a time. Buying and selling on the same day is allowed as long as you never hold more than one share. There are no transaction fees, cooldown days or limit on the number of completed transactions.
Return the maximum total profit after all days, ending with no share held. You may make no trades and earn 0. This is the unlimited-transactions version; do not restrict the answer to one buy and one sell. Do not modify prices.
Function
maxProfitII(prices: int[]) → intExamples
Example 1
prices = [7,1,5,3,6,4]return = 7Buy at1 and sell at5 for4, then buy at3 and sell at6 for3. Two transactions yield total7.
Example 2
prices = [1,2,3,4,5]return = 4One transaction from1 to5 yields4. Splitting this increasing run yields the same total.
Example 3
prices = [7,6,4,3,1]return = 0No positive realized profit is possible, so make no trades and return0.
Constraints
1 <= prices.length <= 30000.0 <= prices[i] <= 10000.- The result is at most
150000000, so all profit calculations fit in a signed 32-bit integer.