Best Time to Buy and Sell Stock

13 May 2026 0 Likes

Problem Description

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

You want to maximize your profit by choosing a single day to buy one stock and choosing a different future day to sell that stock.

Return the maximum profit you can achieve from this transaction. If no profit can be achieved, return 0. You must buy the stock before you sell it.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 when the price is 1 and sell on day 5 when the price is 6. Profit: 6 - 1 = 5. This becomes the maximum possible profit.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: The stock price keeps decreasing, so no profitable transaction is possible. Therefore, the maximum profit becomes: 0
Example 3:
Input: prices = [2,4,1]
Output: 2
Explanation: Buy at price 2 and sell at price 4. Profit: 4 - 2 = 2

Constraints

1. The array contains at least 1 element, and each value inside prices represents a stock price on a particular day. Stock prices are non-negative integers.
2. You may complete at most one transaction, meaning you can buy once and sell once only.
3. If no profitable transaction exists, the answer should be 0.
4. Efficient solutions are expected to process the array in linear time using constant extra space

Understanding the Problem

The problem is asking us to determine the maximum profit that can be earned by buying a stock once and selling it later. Since selling must happen after buying, we always need to track a valid buying day before calculating profit.

A straightforward way to understand the problem is by checking every possible buying and selling pair. For example, in: prices = [7,1,5,3,6,4], if we buy at price 1 and later sell at price 6, the profit becomes: 6 - 1 = 5. This turns out to be the maximum possible profit in the array.

The key observation is that for every selling day, we only care about the minimum price seen before it. If we continuously track the lowest buying price while traversing the array, we can efficiently calculate the best profit possible at every step without checking all pairs repeatedly.

Hints

The first hint is to think about what information is actually required while traversing the array. Instead of remembering every previous price, we only need the minimum buying price seen so far.

For every current price, calculate: currentProfit = currentPrice - minimumPrice. Then continuously update the maximum profit found so far.

This idea allows the problem to be solved efficiently in a single traversal using a greedy-style approach.

Solutions

OPTIMAL

Sliding Window Stock Profit Optimization Solution

This approach efficiently finds the maximum profit using a single traversal of the array. The main idea is to continuously track the lowest buying price seen so far while evaluating every future selling price.

Initially, the first element is treated as the buying price because it is the earliest available day. As we traverse the array, every current element becomes a potential selling price.

If the current selling price is smaller than the previously recorded buying price, we update the buying price because purchasing at a lower value may lead to higher profit later.

Otherwise, we calculate the profit using: sellPrice - buyPrice and compare it with the maximum profit found so far.

For example, in: [7,1,5,3,6,4], when the price becomes 1, it becomes the new minimum buying price. Later, when the price becomes 6, the profit becomes: 6 - 1 = 5, which becomes the maximum profit.

This solution is highly efficient because every element is processed only once while maintaining only the most useful information needed for calculating profit.
public class B_SlidingWindow {
    public int maxProfit(int[] prices) {
        int n = prices.length;

        if (n <= 1) {
            return 0;
        }

        int maxProfit = 0;
        int buyPrice = prices[0];

        for (int i = 1; i < n; i++) {
            int sellPrice = prices[i];

            if (sellPrice < buyPrice) {
                buyPrice = sellPrice;
            } else {
                maxProfit = Math.max(maxProfit, sellPrice - buyPrice);
            }
        }

        return maxProfit;
    }
}
class Solution:
    def maxProfit(self, prices):
        n = len(prices)

        if n <= 1:
            return 0

        max_profit = 0
        buy_price = prices[0]

        for i in range(1, n):
            sell_price = prices[i]

            if sell_price < buy_price:
                buy_price = sell_price
            else:
                max_profit = max(max_profit, sell_price - buy_price)

        return max_profit
Time Complexity
O(n)
Space Complexity
O(1)

Conclusion

The Best Time to Buy and Sell Stock problem is a classic interview problem that teaches efficient array traversal and greedy decision-making techniques. The problem demonstrates how maintaining only the most important information, such as the minimum buying price, can drastically simplify the solution.

Mastering this problem helps build a strong understanding of profit optimization, greedy algorithms, and single-pass traversal strategies, which are commonly used in coding interviews and real-world financial computations.

💬 Comments