122. Best Time to Buy and Sell Stock II

Information

  • Diffculty: Easy

  • Created: 2020-03-11 08:22:00

  • Last Motified: 2020-03-11 08:25:41

  • Tags: Array, Greedy

Intuition

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

Solution

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
            else:
                profit += p - buy_price
                buy_price = p
        return profit