150NeetCode 150

15.Best Time to Buy and Sell Stock

EasyBlind 75Sliding Window ยท 1/6

Problem

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

You may complete at most one transaction: choose one day to buy and a later day to sell. Return the maximum profit you can achieve. If no profitable transaction exists, return 0.

Examples

Input:  prices = [7, 1, 5, 3, 6, 4]
Output: 5
Explanation: Buy on day 1 (price 1) and sell on day 4 (price 6). Profit = 6 - 1 = 5.
             Buying at 1 and selling at 7 is not allowed because day 0 comes before day 1.
Input:  prices = [7, 6, 4, 3, 1]
Output: 0
Explanation: Prices only fall, so every transaction loses money. Do nothing โ†’ profit 0.

Constraints

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

๐Ÿ’ก Key Insight

For any selling day j, the best buying day is simply the cheapest day before j. So we do not need to try every pair โ€” we sweep left to right, remember the minimum price seen so far, and at each day ask "what if I sold today?". One pass, constant memory.

Brute Force

TimeO(nยฒ)SpaceO(1)

Intuition

Try every possible pair (buy day i, sell day j) with i < j and keep the largest prices[j] - prices[i].

Algorithm

  1. Set maxProfit = 0.
  2. For each i from 0 to n - 1:
  3. For each j from i + 1 to n - 1, update maxProfit = max(maxProfit, prices[j] - prices[i]).
  4. Return maxProfit.

Visualization

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

i=0 (7): 1-7, 5-7, 3-7, 6-7, 4-7  โ†’ all negative
i=1 (1): 5-1=4, 3-1=2, 6-1=5 โœ“, 4-1=3  โ†’ best = 5
i=2 (5): 3-5, 6-5=1, 4-5           โ†’ best stays 5
...
answer = 5

Code

java
class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        for (int i = 0; i < prices.length; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                // buy on day i, sell on a later day j
                maxProfit = Math.max(maxProfit, prices[j] - prices[i]);
            }
        }
        return maxProfit;
    }
}

Complexity

  • Time: O(nยฒ) โ€” every pair of days is examined; too slow for n = 10^5.
  • Space: O(1) โ€” only a running maximum.

Complexity Comparison

Approach Time Space
Brute Force O(nยฒ) O(1)
Two Pointers O(n) O(1)
Running Minimum O(n) O(1)

Common Pitfalls

  • Taking max(prices) - min(prices) โ€” the maximum may occur before the minimum, which would mean selling before buying.
  • Returning a negative number when prices only fall; the answer must be at least 0 (you may skip trading).
  • Updating maxProfit before minPrice is fine here, but updating minPrice with a future value before computing profit is not โ€” always compare against prices from earlier (or the same) day.
  • Using a nested loop "because n is small" โ€” n goes up to 10^5, so O(nยฒ) times out.