LeetCode ยท #121

Best Time to Buy and Sell Stock Solution

Given an array prices where prices[i] is the price on day i, return the maximum profit from one buy and one sell.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #121

๐Ÿ—๏ธ

Pattern

Sliding Window โ€” track min so far

You are given an array prices where prices[i] is the price of a stock on day i. You want to maximize profit by choosing a single day to buy and a single future day to sell. Return the maximum profit, or 0 if no profit is possible.

Example
Input: prices = [7, 1, 5, 3, 6, 4] Output: 5 // Buy on day 1 (price=1), sell on day 4 (price=6) โ†’ profit = 5
Constraints
โ€ข 1 โ‰ค prices.length โ‰ค 10โต โ€ข 0 โ‰ค prices[i] โ‰ค 10โด
02
Section Two ยท Approach 1

Brute Force โ€” O(nยฒ)

For every day i, check every future day j > i and compute prices[j] - prices[i]. Track the maximum difference.

Problem: O(nยฒ) pairs. We only need to track the minimum price seen so far โ€” at each day, the best profit is prices[i] - minSoFar. One pass, O(1) space.
Java โ€” Brute Force
class Solution { public int maxProfit(int[] prices) { int max = 0; for (int i = 0; i < prices.length; i++) for (int j = i + 1; j < prices.length; j++) max = Math.max(max, prices[j] - prices[i]); return max; } }
Python โ€” Brute Force
class Solution: def maxProfit(self, prices: list[int]) -> int: max_profit = 0 for i in range(len(prices)): for j in range(i + 1, len(prices)): max_profit = max(max_profit, prices[j] - prices[i]) return max_profit
MetricValue
TimeO(nยฒ)
SpaceO(1)
03
Section Three ยท Approach 2

One Pass โ€” O(n)

Scan left to right, tracking the minimum price seen so far. At each day, compute profit as price - minPrice. Update the maximum profit. The minimum price acts as the left pointer of a sliding window โ€” it resets whenever a cheaper buy opportunity is found.

๐Ÿ’ก Mental model: You're walking down a timeline of prices. You carry a sign showing the cheapest price you've ever passed. At each new day, you ask: "If I had bought at that cheapest price, how much would I make selling today?" You record the best answer. If today's price is even cheaper, you update your sign.
Algorithm
  • Step 1: minPrice = โˆž, maxProfit = 0.
  • Step 2: For each price: update minPrice = min(minPrice, price).
  • Step 3: Update maxProfit = max(maxProfit, price - minPrice).
  • Step 4: Return maxProfit.
๐ŸŽฏ When to recognize this pattern:
  • Any problem asking for the maximum difference between two elements where the smaller must come first โ€” think track-min-so-far.
  • This is a degenerate sliding window where the left boundary only moves forward when a new minimum is found.
  • The same idea extends to maximum subarray (Kadane's algorithm) and stock problems with multiple transactions.
04
Section Four ยท Trace

Visual Walkthrough

Trace through prices = [7, 1, 5, 3, 6, 4]:

One Pass โ€” track min price, compute profit at each step
PRICES 7 1 5 3 6 4 day 0: price=7, min=7, profit=0, maxProfit=0 day 1: price=1, min=1 โ† new min!, profit=0, maxProfit=0 day 2: price=5, min=1, profit=4, maxProfit=4 day 3: price=3, min=1, profit=2, maxProfit=4 day 4: price=6, min=1, profit=5, maxProfit=5 โ† best! day 5: price=4, min=1, profit=3, maxProfit=5 Answer: 5 โ€” buy at 1, sell at 6 โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” One Pass
class Solution { public int maxProfit(int[] prices) { int minPrice = Integer.MAX_VALUE; int maxProfit = 0; for (int price : prices) { minPrice = Math.min(minPrice, price); maxProfit = Math.max(maxProfit, price - minPrice); } return maxProfit; } }
Python โ€” One Pass
class Solution: def maxProfit(self, prices: list[int]) -> int: min_price = float('inf') max_profit = 0 for price in prices: min_price = min(min_price, price) max_profit = max(max_profit, price - min_price) return max_profit
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpaceTrade-off
Brute ForceO(nยฒ)O(1)Check all buy/sell pairs
One Pass โ† optimal O(n) O(1) Track min price, compute profit at each step
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Decreasing prices[7, 6, 4, 3, 1]No profit possible โ†’ return 0. Profit is never positive.
Single day[5]Can't buy and sell on same day โ†’ 0.
All same price[3, 3, 3]Profit = 0 everywhere.
Best at end[2, 4, 1, 7]Min shifts to 1 on day 2, best profit at day 3: 7-1=6.
Best at start[1, 5, 2, 3]Min stays 1, best profit is 5-1=4 on day 1.
โš  Common Mistake: Computing max(prices) - min(prices) without checking that the min comes before the max. The minimum price might occur after the maximum, making the trade impossible. Tracking minSoFar as you scan left-to-right guarantees you only consider valid buy-before-sell pairs.

โ† Back to Sliding Window problems