Zero To DSAZero To DSA
Privacy Policy
Jump GameMeeting Rooms II

Best Time to Buy and Sell Stock II

medium
Time: O(n)
Space: O(1)

You are given an array prices where prices[i] is the price on day i. You may complete as many transactions as you like (buy one and sell one share multiple times). Return the maximum profit.

Constraints

  • 1 <= prices.length <= 3 * 10⁴

Examples

Input: prices = [7,1,5,3,6,4]
Output: 7
Buy at 1, sell at 5 (profit 4). Buy at 3, sell at 6 (profit 3). Total = 7.
Input: prices = [1,2,3,4,5]
Output: 4
Buy at 1, sell at 5.