Coding interview problems › Arrays & Hashing

#️⃣ Arrays & Hashing Easy

Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock explained: track the cheapest price so far and the best profit in one O(n) pass. Tested Python, common mistakes, live visual.

Also searched as: stock buy and sell maximum profit · max profit one transaction

📈

Try it live Free

Prefix Sums & Kadane

Watch Kadane scan once and carry a running value. Here the running value is the lowest price so far, and each day's profit is today minus that low.

Open the playground →

The problem

You get a list of daily stock prices. You may buy on one day and sell on a later day, once. Return the maximum profit you can make, or 0 if no profitable trade exists.

Inputprices = [7, 1, 5, 3, 6, 4]
Output5

Buy at 1, sell at 6.

Inputprices = [7, 6, 4, 3, 1]
Output0

Prices only fall, so do not trade.

The key insight

If you sell on day j, the best buy day is just the cheapest day before j. So walk once, remember the minimum price seen so far, and at each day check the profit of selling today. It is Kadane's idea in disguise: the running minimum plays the role of dropping a bad past.

Brute force first: Trying every buy day with every later sell day is O(n²).

Step-by-step approach

  1. Set low to infinity and best = 0.
  2. For each price p: if p < low, update low = p.
  3. Otherwise compute p - low and update best if it is larger.
  4. Return best.

Python solution

PYTHON 3tested
def max_profit(prices):
    low = float("inf")
    best = 0
    for p in prices:
        if p < low:
            low = p                # cheapest buy so far
        else:
            best = max(best, p - low)
    return best

Complexity

TimeO(n)
SpaceO(1)

A single pass that keeps two numbers: the lowest price so far and the best profit.

Common mistakes

Frequently asked questions

What is the time and space complexity of Best Time to Buy and Sell Stock?

O(n) time and O(1) space with the running-minimum solution. The pair-checking brute force is O(n²).

How is this related to Kadane's algorithm?

Take the daily price differences; the best profit is the maximum subarray sum of those differences (or 0). The running-minimum version is the same idea without building the difference array.

What if I can trade many times?

With unlimited transactions and no fees, add up every positive day-to-day increase. That greedy sum is the maximum profit.

Preparing for placements?

Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.

All coding interview problems More Arrays & Hashing Hash Tables lab Placement prep guides

Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.