← Back to Leo Academy Masterclass

Problem #122: Best Time to Buy and Sell Stock II

Medium Array & String

Intuition & Strategy Breakdown

Greedily accumulate profit whenever price[i] > price[i-1] (buy low on day i-1 and sell high on day i).

Python Solution

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

Java Solution

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                profit += prices[i] - prices[i - 1];
            }
        }
        return profit;
    }
}
Watch Interactive Video on Leo Academy Main App