← Back to Leo Academy Masterclass

Problem #121: Best Time to Buy and Sell Stock

Easy Array & String

Intuition & Strategy Breakdown

Track minimum stock price seen so far and maximum profit achievable by selling at current price (profit = price - min_price).

Python Solution

class Solution:
    def maxProfit(self, prices: list[int]) -> int:
        l, r = 0, 1
        max_p = 0
        while r < len(prices):
            if prices[l] < prices[r]:
                profit = prices[r] - prices[l]
                max_p = max(max_p, profit)
            else:
                l = r
            r += 1
        return max_p

Java Solution

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int price : prices) {
            if (price < minPrice) {
                minPrice = price;
            } else if (price - minPrice > maxProfit) {
                maxProfit = price - minPrice;
            }
        }
        return maxProfit;
    }
}
Watch Interactive Video on Leo Academy Main App