DEV Community

Aniket Vaishnav
Aniket Vaishnav

Posted on

๐Ÿ“ˆ Best Time to Buy and Sell Stock (LeetCode 121)

๐Ÿง  Problem Statement

Video Explain

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

Your goal is to maximize profit by choosing a single day to buy one stock and a different future day to sell that stock.

If no profitable transaction is possible, return 0.


๐Ÿงพ Examples

Example 1:

Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5
Explanation: Buy on day 2 (price = 1), sell on day 5 (price = 6). Profit = 6 - 1 = 5.
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: prices = [7, 6, 4, 3, 1]
Output: 0
Explanation: No future price is higher than the earlier prices.
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

๐Ÿ’ก Intuition

We need to buy low and sell high, but with a key restriction:

We must buy before we sell.

So weโ€™re looking for the maximum difference between two prices prices[j] - prices[i] where j > i.


๐Ÿชœ Step-by-Step Approach

๐Ÿ” One-Pass Greedy Algorithm

  • Track the minimum price so far as you iterate.
  • For each price, calculate the profit if you bought at the minimum and sold today.
  • Keep updating the maximum profit found.

โœ… Why this works

We always look backward to see the best time we could have bought the stock before today.

This ensures we never violate the "buy before sell" rule.


๐Ÿงฎ Dry Run

Let's walk through prices = [7, 1, 5, 3, 6, 4]

Day Price Min Price So Far Profit if Sold Today Max Profit
1 7 7 0 0
2 1 1 โœ… 0 0
3 5 1 4 4 โœ…
4 3 1 2 4
5 6 1 5 โœ… 5 โœ…
6 4 1 3 5

๐Ÿง‘โ€๐Ÿ’ป C++ Code

#include <vector>
#include <algorithm>
using namespace std;

int maxProfit(vector<int>& prices) {
    int minPrice = INT_MAX;
    int maxProfit = 0;

    for (int price : prices) {
        minPrice = min(minPrice, price); // Track lowest price so far
        maxProfit = max(maxProfit, price - minPrice); // Check today's profit
    }

    return maxProfit;
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿง‘โ€๐Ÿ’ป Java Code

public class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;

        for (int price : prices) {
            minPrice = Math.min(minPrice, price); // Track lowest price so far
            maxProfit = Math.max(maxProfit, price - minPrice); // Check today's profit
        }

        return maxProfit;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ Time & Space Complexity

Metric Value
Time Complexity O(n)
Space Complexity O(1)

๐Ÿ”š Final Thoughts

This problem is a classic sliding window or greedy pattern.

It teaches a powerful lesson: Track the best "buy" dynamically, rather than trying every pair.

Let me know if you'd like
https://www.youtube.com/watch?v=COJ-KY7DIOs

Top comments (0)