Best Time to Buy and Sell Stock [Easy]

15 Aug 2026 2 min read
2
The Best Time to Buy and Sell Stock problem requires finding the maximum profit that can be achieved by buying a stock on one day and selling it on a later day.

Problem

You are given an integer array prices, where prices[i] is the price of a given stock on the ith day.

Choose a single day to buy one stock and a different future day to sell that stock to maximize your profit. Return the maximum profit you can achieve. If no profit is possible, return 0.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

prices = [7,1,5,3,6,4] 

Output

5 

Solution

This solution traverses the array once while keeping track of the lowest stock price seen so far.

For each day's price, it calculates the profit that would be earned by selling the stock on that day after buying it at the lowest price seen so far.

If this profit is greater than the current maximum profit, the maximum profit is updated. The minimum price is also updated whenever a lower price is encountered.

By continuously tracking the lowest buying price and the best profit, we can find the maximum possible profit in a single traversal.
public int maxProfit(int[] prices) {
    int minPrice = Integer.MAX_VALUE;
    int maxProfit = 0;

    for (int price : prices) {
        // Update the lowest buying price.
        minPrice = Math.min(minPrice, price);

        // Calculate and update the maximum profit.
        maxProfit = Math.max(maxProfit, price - minPrice);
    }
    return maxProfit;
}

Complexity

The algorithm scans the array only once, processing each element exactly once. This results in a linear time complexity of O(n).

Only two variables are used to track the minimum price and maximum profit, so the extra space complexity is O(1).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion