KatInterview

121. Best Time to Buy and Sell Stock

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the maximum profit that can be obtained from a single transaction (one buy and one sell) of a stock. We are given an array of stock prices for consecutive days. The key constraint is that we must buy the stock on a day before we sell it. If no profit can be made, we should return 0.

Solution

Best Time to Buy and Sell Stock in Python

import math

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # Initialize min_price to a very large value to ensure the first price becomes the minimum.
        min_price = math.inf
        # Initialize max_profit to 0. Profit cannot be negative; if no profitable trade is possible, we return 0.
        max_profit = 0

        for price in prices:
            # If the current price is lower than our recorded minimum, it's a better day to buy.
            if price < min_price:
                min_price = price
            # Otherwise, check if selling today yields a higher profit than we've seen before.
            # This profit is from selling at the current `price` after theoretically buying at `min_price`.
            elif price - min_price > max_profit:
                max_profit = price - min_price
        
        return max_profit

Best Time to Buy and Sell Stock in Java

class Solution {
    public int maxProfit(int[] prices) {
        // Initialize minPrice to a very large value to ensure the first price is smaller.
        int minPrice = Integer.MAX_VALUE;
        // Initialize maxProfit to 0, as profit cannot be negative. If no profitable transaction is found, 0 is the correct answer.
        int maxProfit = 0;

        // Iterate through each price in the array.
        for (int price : prices) {
            // Check if the current price is a new minimum buy price.
            if (price < minPrice) {
                minPrice = price; // Update the minimum price.
            } 
            // If it's not a new minimum, check if selling at this price gives a better profit.
            else if (price - minPrice > maxProfit) {
                // The profit from selling today is current price - lowest price found so far.
                maxProfit = price - minPrice; // Update the maximum profit.
            }
        }
        
        return maxProfit;
    }
}

Best Time to Buy and Sell Stock in C++

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        // Initialize minPrice to a very large value.
        int minPrice = std::numeric_limits<int>::max();
        // Initialize maxProfit to 0. If no profitable transaction is found, 0 is the answer.
        int maxProfit = 0;

        // Iterate through each price in the array.
        for (int price : prices) {
            // Check if we found a new, lower price to buy.
            if (price < minPrice) {
                minPrice = price;
            } 
            // Otherwise, check if selling at the current price would yield a new max profit.
            // Profit is calculated as current price minus the lowest price we could have bought at.
            else if (price - minPrice > maxProfit) {
                maxProfit = price - minPrice;
            }
        }

        return maxProfit;
    }
};

Best Time to Buy and Sell Stock in TypeScript

function maxProfit(prices: number[]): number {
    // Initialize minPrice to a very large number.
    let minPrice = Infinity;
    // Initialize maxProfit to 0. Profit can't be negative.
    let maxProfit = 0;

    // Iterate through the prices array.
    for (const price of prices) {
        // If the current price is lower than our recorded minimum, it's a better day to buy.
        if (price < minPrice) {
            minPrice = price;
        } 
        // Otherwise, check if selling today yields a higher profit than we've seen before.
        else if (price - minPrice > maxProfit) {
            maxProfit = price - minPrice;
        }
    }

    return maxProfit;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.