SDE & MLE Prep

122. Best Time to Buy and Sell Stock II

Problem

prices[i] is a stock's price on day i. Buy and sell as often as you like, holding at most one share at a time (you may sell and buy again on the same day). Return the maximum profit.

Example: [7,1,5,3,6,4] → 7 (buy 1 sell 5, buy 3 sell 6); [1,2,3,4,5] → 4

Unlimited transactions → collect every positive day-to-day increase.

Complexity: O(n).

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        return sum(max(0, b - a) for a, b in zip(prices, prices[1:]))