122. Best Time to Buy and Sell Stock II

Updated: 2024-03-12
1 min read

On This Page

LeetCode problem

To solve this problem, we can use a greedy approach.

The idea is to keep adding the profit whenever the price on the next day is higher than the price on the current day.

This way, we will maximize profit.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0

        for i in range(1, len(prices)):
            if prices[i] > prices[i - 1]:
                profit += prices[i] - prices[i - 1]
        return profit

LeetCode Editorial: