Article start
DSA Course: Interview Patterns and Problem Solving
Module 1: Arrays

Best Time to Buy and Sell Stock: Greedy Pattern

Track the lowest price seen so far and decide the best profit if you sell today.

May 28, 2026·38

Learning Outcome

After this lesson, you should be able to convert the "choose buy and sell days" brute force into a one-pass greedy scan.

Problem Statement

Given prices, where prices[i] is the stock price on day i, return the maximum profit from one buy and one later sell. If no profit is possible, return 0.

InputOutputWhy
[7, 1, 5, 3, 6, 4]5Buy at 1, sell at 6.

Brute Force Approach

Try every buy day and every later sell day. Compute prices[sell] - prices[buy] and keep the best profit.

This checks the rule correctly, but it costs O(n^2) because every day can be paired with many later days.

Optimized Approach

While scanning left to right, keep the minimum price seen so far. If you sell today, the best valid buy day must be one of the earlier days, so today profit is price - minPrice.

This works because every sell day only needs the cheapest earlier buy day, not all earlier days.

Exact Pseudocode

minPrice = infinity
best = 0
for price in prices:
  minPrice = min(minPrice, price)
  best = max(best, price - minPrice)
return best

Reference Code

class Solution:
    def maxProfit(self, prices):
        min_price = float("inf")
        best = 0

        for price in prices:
            min_price = min(min_price, price)
            best = max(best, price - min_price)

        return best

Sample Dry Run

priceminPriceprofit if sold todaybest
7700
1100
5144
3124
6155
4135

Complexity

MeasureValueReason
TimeO(n)One scan over all prices.
SpaceO(1)Only two variables are stored.

Edge Cases

  • Prices always decrease, such as [7, 6, 4, 3, 1].
  • Only one day or empty input if allowed by platform constraints.
  • Best buy day appears before the best sell day, not after.

Interview Checklist

  • Emphasize "buy before sell".
  • Track the cheapest price seen so far.
  • Return 0 when no positive profit exists.

FAQs

Why is this greedy?

For each sell day, the best decision only depends on the cheapest valid buy day seen before it.

Can I sell before buying?

No. The left-to-right scan enforces that the buy price comes from an earlier day.

What if all prices fall?

The best profit remains 0.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.