Best Time to Buy and Sell Stock: Amazon's Favorite Easy Problem
If you could only prepare for one Easy problem before an Amazon interview, it should be Best Time to Buy and Sell Stock — LeetCode 121. It is the single most-asked Easy question at Amazon and consistently appears in top-10 Easy lists across all major tech companies. The problem is simple to state, impossible to fumble if you know the pattern, and a perfect warm-up for harder greedy and dynamic programming problems.
The best time to buy and sell stock leetcode problem asks you to find the maximum profit from a single buy-sell transaction given an array of daily stock prices. You must buy before you sell — no time travel allowed. Despite the straightforward setup, many candidates stumble because they reach for nested loops when a single pass is all you need.
In this walkthrough, you will see why the brute force fails at scale, how the one-pass greedy solution works, and why this problem is secretly the same pattern as Kadane's algorithm. By the end, you will solve it in four lines of code and understand the deeper principle behind it.
Understanding the Problem — One Buy, One Sell
You are given an array prices where prices[i] is the price of a stock on day i. You want to maximize your profit by choosing a single day to buy and a later day to sell. If no profit is possible, return 0. That is the entire problem statement for LeetCode 121.
The key constraint is that you must buy before you sell. You cannot sell on day 3 and buy on day 5 — the buy must come first chronologically. This means you are looking for the largest difference prices[j] - prices[i] where j > i. If every price is lower than the previous one (a strictly decreasing array), no profitable transaction exists and the answer is 0.
Consider the classic example: prices = [7, 1, 5, 3, 6, 4]. The optimal strategy is to buy on day 2 (price = 1) and sell on day 5 (price = 6) for a profit of 5. Notice that you do not buy at the global minimum and sell at the global maximum — you buy at the minimum that appears before the maximum selling opportunity.
Did You Know?
Best Time to Buy and Sell Stock (#121) is the #1 most-asked Easy problem at Amazon and a top 10 Easy across all companies — it's the go-to warm-up question.
Brute Force — Check Every Pair
The most intuitive approach is to check every possible buy-sell pair. For each day i, look at every future day j and compute prices[j] - prices[i]. Track the maximum profit across all valid pairs. This directly translates the problem statement into code.
The brute force uses two nested loops. The outer loop picks the buy day, the inner loop picks the sell day. You compute the profit for each pair and update your running maximum. The logic is correct and easy to verify, but the performance is unacceptable for large inputs.
With two nested loops iterating over n prices, the time complexity is O(n^2). For the constraint n <= 100,000 in LeetCode 121, this means up to 10 billion operations — far too slow. The brute force will time out on large test cases. You need a way to eliminate the inner loop entirely.
- Time complexity: O(n^2) — check every pair of days
- Space complexity: O(1) — only track max profit
- Correct but too slow for n = 100,000
- The inner loop is redundant — you only need the minimum price seen so far
One-Pass Solution — Track the Minimum Price So Far
The key insight is that you do not need to check every pair. As you scan left to right, you only need to know one thing: what is the cheapest price you have seen so far? At each day, the best profit you could make by selling today is today's price minus the minimum price seen before today. Track that running maximum and you have your answer.
Initialize minPrice to Infinity (or the first element) and maxProfit to 0. Iterate through the prices array once. At each price, update minPrice if the current price is lower. Then compute the profit as current price minus minPrice, and update maxProfit if this profit is larger. After one pass, maxProfit holds the answer.
This buy sell stock one pass approach runs in O(n) time and O(1) space. You visit each price exactly once and store only two variables. The entire solution is four lines inside the loop — initialize, iterate, update min, update max. That simplicity is exactly why interviewers love it as a warm-up.
For the example prices = [7, 1, 5, 3, 6, 4]: on day 1, minPrice drops to 7. On day 2, minPrice drops to 1. On day 3, profit = 5 - 1 = 4. On day 4, profit = 3 - 1 = 2. On day 5, profit = 6 - 1 = 5 (new max). On day 6, profit = 4 - 1 = 3. The answer is 5.
- Time complexity: O(n) — single pass through the array
- Space complexity: O(1) — two variables: minPrice and maxProfit
- Initialize minPrice = Infinity, maxProfit = 0
- At each step: minPrice = min(minPrice, price), maxProfit = max(maxProfit, price - minPrice)
Pro Tip
The entire solution is 4 lines: initialize minPrice=Infinity and maxProfit=0, iterate through prices, update minPrice and maxProfit. The simplicity is what makes it a great interview warm-up.
Why This Is a Greedy Algorithm
The one-pass solution is a textbook greedy algorithm. At every step, you make the locally optimal choice: always treat the cheapest price seen so far as your buy point. You never go back and reconsider a previous decision. This greedy choice happens to produce the globally optimal answer because the problem has optimal substructure — the best profit ending at day i depends only on the minimum price in days 0 through i-1.
This buy sell stock greedy pattern is closely related to Kadane's algorithm for maximum subarray sum. If you transform the prices array into a daily changes array (prices[i] - prices[i-1]), then finding the maximum profit is identical to finding the maximum contiguous subarray sum. Both problems rely on the same principle: track a running best and reset when continuing is worse than starting fresh.
Understanding this connection is more valuable than memorizing the solution. The "track min/max so far" pattern appears in dozens of problems: maximum subarray, trapping rain water, container with most water, and product of array except self. Once you internalize this one principle, you unlock an entire family of O(n) solutions.
Edge Cases and Variants
Before submitting, make sure your solution handles the edge cases. A strictly decreasing prices array like [5, 4, 3, 2, 1] should return 0 — no profitable transaction exists. A single-element array should also return 0 since you cannot both buy and sell. An array where all prices are the same returns 0 as well.
LeetCode has several follow-up problems in the Buy and Sell Stock family that test deeper understanding. Buy and Sell Stock II (#122) allows unlimited transactions — the greedy strategy changes to summing all positive differences. Buy and Sell Stock III (#123) limits you to at most two transactions and requires dynamic programming with state tracking. Buy and Sell Stock with Cooldown (#309) adds a one-day cooldown between selling and buying again.
Each variant builds on the intuition from problem #121, but the solutions diverge significantly. Interviewers sometimes use #121 as a warm-up and then ask a follow-up from #122 or #309 in the same round. Knowing the family tree helps you anticipate where the conversation is heading.
- Decreasing prices [5,4,3,2,1] — return 0, no profit possible
- Single element — return 0, cannot buy and sell
- Buy/Sell II (#122) — unlimited transactions, sum all gains
- Buy/Sell III (#123) — at most 2 transactions, DP with states
- Buy/Sell with Cooldown (#309) — must wait one day after selling
Watch Out
Don't confuse Buy/Sell I (#121, one transaction) with Buy/Sell II (#122, unlimited transactions) — they have completely different solutions. #121 is greedy, #122 is also greedy but with a different strategy.
What Best Time to Buy and Sell Stock Teaches You
LeetCode 121 is more than just a warm-up problem. It teaches the fundamental "track min/max so far" pattern that appears across dozens of interview questions. Every time you see an array problem asking for the maximum difference, maximum subarray, or optimal single transaction, this same principle applies: maintain a running extreme and compute the best result at each step.
The problem also demonstrates why greedy algorithms work when they do. The greedy choice — always buying at the cheapest price seen so far — works because there is no benefit to buying at a higher price. This seems obvious in hindsight, but recognizing when a greedy approach is valid versus when you need dynamic programming is a critical interview skill.
Practice this problem until you can write the solution from memory in under two minutes. Then use YeetCode flashcards to drill the pattern alongside related problems like Maximum Subarray (#53) and Container With Most Water (#11). The goal is not to memorize the code but to internalize the pattern so deeply that you recognize it instantly in unfamiliar problems.