121. Best Time To Buy And Sell Stock

6 min read

Mastering the Best Time to Buy and Sell Stock problem is a rite of passage for anyone preparing for technical interviews. Known widely as LeetCode 121, this question tests your ability to optimize a brute-force approach into an elegant, linear-time solution. It introduces the fundamental concept of tracking a running minimum (or maximum) to calculate the best possible outcome in a single pass Easy to understand, harder to ignore..

This guide provides a deep dive into the problem statement, the intuition behind the optimal approach, step-by-step algorithm walkthroughs, complexity analysis, and clean code implementations in Python, Java, and C++.

Understanding the Problem Statement

Before writing code, we must define the constraints clearly. You are given an integer array prices where prices[i] represents the price of a given stock on the i-th day.

The Goal: Maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock That's the part that actually makes a difference. But it adds up..

The Constraints:

  1. You must buy before you sell (index buy < index sell).
  2. You may complete at most one transaction (one buy, one sell).
  3. If no profit is possible, return 0.

Example 1:

  • Input: prices = [7,1,5,3,6,4]
  • Output: 5
  • Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5.

Example 2:

  • Input: prices = [7,6,4,3,1]
  • Output: 0
  • Explanation: The price decreases every day; no transaction yields profit.

Approach 1: Brute Force (The Naive Solution)

The most intuitive way to solve this is to check every possible pair of buy and sell days And it works..

Algorithm

  1. Initialize max_profit = 0.
  2. Loop through every index i from 0 to n-1 (Buy Day).
  3. Nest a loop through every index j from i+1 to n-1 (Sell Day).
  4. Calculate current_profit = prices[j] - prices[i].
  5. Update max_profit = max(max_profit, current_profit).
  6. Return max_profit.

Complexity Analysis

  • Time Complexity: O(n²). For an array of size n, we evaluate roughly n²/2 pairs. This will Time Limit Exceed (TLE) on large inputs (typically n > 10⁴).
  • Space Complexity: O(1). Only constant extra variables are used.

Approach 2: One Pass - Tracking Minimum Price (Optimal)

The brute force recalculates differences repeatedly. The key insight is: To maximize profit selling on day i, you must have bought at the lowest price seen before day i.

We can solve this in a single forward pass by maintaining two variables:

  1. Now, min_price: The minimum price encountered so far. 2. max_profit: The maximum profit achievable so far.

Algorithm Walkthrough

  1. Initialize min_price to infinity (or prices[0]) and max_profit to 0.
  2. Iterate through the prices array.
  3. Update Minimum: min_price = min(min_price, current_price).
  4. Calculate Potential Profit: profit = current_price - min_price.
  5. Update Maximum: max_profit = max(max_profit, profit).
  6. Return max_profit.

Dry Run on prices = [7, 1, 5, 3, 6, 4]

Day Price min_price (so far) Current Profit (Price - min_price) max_profit
0 7 7 0 0
1 1 1 0 0
2 5 1 4 4
3 3 1 2 4
4 6 1 5 5
5 4 1 3 5

Real talk — this step gets skipped all the time Most people skip this — try not to..

Final Result: 5.

Complexity Analysis

  • Time Complexity: O(n). We traverse the list exactly once.
  • Space Complexity: O(1). Only two integer variables are stored.

Approach 3: Kadane’s Algorithm Perspective (Difference Array)

This problem is mathematically equivalent to finding the Maximum Subarray Sum (LeetCode 53) on the difference array But it adds up..

If we create an array diff where diff[i] = prices[i] - prices[i-1], the profit from buying at i and selling at j is simply the sum of diff[i+1] ... In real terms, diff[j]. Finding the max profit becomes finding the maximum subarray sum in diff. Since we only need the previous sum, we can do this in O(1) space.

No fluff here — just what actually works The details matter here..

Algorithm

  1. max_profit = 0, current_profit = 0.
  2. Loop i from 1 to n-1.
  3. current_profit = max(0, current_profit + prices[i] - prices[i-1]).
  4. max_profit = max(max_profit, current_profit).
  5. Return max_profit.

This approach is conceptually powerful because it generalizes to "Best Time to Buy and Sell Stock II" (multiple transactions) instantly.

Code Implementations

Python (Clean & Pythonic)

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = float('inf')
        max_profit = 0
        
        for price in prices:
            # Update the minimum price seen so far
            min_price = min(min_price, price)
            # Calculate profit if sold today
            profit = price - min_price
            # Update max profit
            max_profit = max(max_profit, profit)
            
        return max_profit

Java (Standard OOP Style)

class Solution {
    public int maxProfit(int[] prices) {

### Completing the Java Implementation  

```java
class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;                     // no transaction possible
        }

        int minPrice = Integer.MAX_VALUE; // current lowest buying price
        int maxProfit = 0;                // best profit seen so far

        for (int price : prices) {
            // keep the smallest price encountered up to the current day
            minPrice = Math.min(minPrice, price);
            // profit if we sold today after buying at minPrice
            int profit = price - minPrice;
            // improve the best profit if this opportunity is larger
            maxProfit = Math.max(maxProfit, profit);
        }

        return maxProfit;
    }
}

The logic mirrors the Python version: a single pass keeps track of the lowest price seen so far and the best achievable profit, updating both in constant time per element.


Equivalent Solutions in Other Languages

C++ (using std::vector)

class Solution {
public:
    int maxProfit(vector& prices) {
        if (prices.empty()) return 0;

        int minPrice = INT_MAX;
        int maxProfit = 0;

        for (int p : prices) {
            minPrice = min(minPrice, p);
            maxProfit = max(maxProfit, p - minPrice);
        }
        return maxProfit;
    }
};

JavaScript (ES6)

class Solution {
    maxProfit(prices) {
        if (!prices.length) return 0;

        let minPrice = Infinity;
        let maxProfit = 0;

        for (const p of prices) {
            minPrice = Math.min(minPrice, p);
            const profit = p - minPrice;
            maxProfit = Math.max(maxProfit, profit);
        }
        return maxProfit;
    }
}

All three snippets share the same linear‑time, constant‑space characteristics Nothing fancy..


Edge‑Case Considerations

  • Empty or single‑element input – there is no possibility to buy and sell, so the function should immediately return 0.
  • Monotonically decreasing prices – the minimum price keeps moving forward, but every potential profit is negative; the algorithm naturally caps profit at 0.
  • Constant price series – the minimum never changes, resulting in a profit of 0, which matches the definition of “no profitable transaction.”

These scenarios are handled without extra branches because the core updates (min and max) inherently manage them.


Conclusion

The optimal solution for the “best time to buy and sell stock” problem relies on a single traversal that maintains two pieces of state: the lowest price observed so far and the greatest profit achievable up to the current point. This yields O(n) time complexity and O(1) auxiliary space, satisfying the requirements for large input sizes. Which means the approach translates cleanly across languages, making it a versatile pattern for similar “maximum subarray” style questions. By adhering to the simple update rules, the implementation remains both concise and solid, handling all edge conditions automatically Worth knowing..

Hot New Reads

Just Shared

Keep the Thread Going

What Others Read After This

Thank you for reading about 121. Best Time To Buy And Sell Stock. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home