Best Time to Buy and Sell Stock II

Problem Id: 122 Difficulty: Easy Tag: Array Tag: Greedy


To get the most profit, we need to seize every opportunity.


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0

        buy_price = prices[0]
        profit = 0
        for p in prices:
            if p <= buy_price:
                buy_price = p
                profit += p - buy_price
                buy_price = p
        return profit