Skip to content

Interview Solver

FeaturesPricingHelp
Sign In
FeaturesPricingHelpSign In
  1. Interview Questions
  2. /
  3. Problems
  4. /
  5. Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock

Pick one day to buy and a later day to sell for the biggest profit. A one-pass problem built on tracking the running minimum. Solve it below in Python or JavaScript, then read the walkthrough.

EasyArrayDynamic ProgrammingAsked at 163 companies incl. Google, Amazon, Meta

Problem

You're given an array prices where prices[i] is a stock's price on day i. You may buy one share on one day and sell it on a later day.

Return the largest profit you can make from a single buy and sell. If no trade makes money, return 0.

Example 1

Input
prices = [9, 4, 6, 2, 8, 5]
Output
6

Buy on day 3 at 2 and sell on day 4 at 8.

Example 2

Input
prices = [10, 8, 8, 3]
Output
0

The price never rises, so the best choice is not to trade.

Example 3

Input
prices = [3, 11, 1, 5]
Output
8

The lowest price, 1, comes too late to beat buying at 3 and selling at 11.

Constraints

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴

Practice

1
2
3
4

Runs 12 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.

Get asked Best Time to Buy and Sell Stock in a real interview?

Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.

Start Free Trial

How to solve Best Time to Buy and Sell Stock

Pattern: Running minimum

Fix the day you sell. The best day to have bought is simply the cheapest day before it. So if, as you walk forward, you always know the lowest price so far, every day's best possible profit is price - lowest_so_far, and the answer is the largest of those.

That's why the answer to [3, 11, 1, 5] isn't "buy at the global minimum": the minimum of 1 arrives after the peak. Tracking the minimum so far respects the buy-before-sell order automatically.

Approach 1: Brute force: every buy/sell pair

Try every pair i < j and keep the largest prices[j] - prices[i]. Correct, but quadratic, which is too slow at 10⁵ days.

Time O(n²) · Space O(1)

Approach 2: One pass with the running minimum

Keep lowest (the cheapest price seen so far) and best (the best profit so far, starting at 0). For each price:

  1. Update best = max(best, price - lowest).
  2. Update lowest = min(lowest, price).

Checking profit before updating the minimum means you never sell on the day you buy, though with the profit floored at 0 the order doesn't change the answer.

Time O(n) · Space O(1)

ApproachTimeSpace
Brute force: every buy/sell pairO(n²)O(1)
One pass with the running minimumO(n)O(1)

Solution code

Try the practice editor first. Both solutions pass every test above.

▸Best Time to Buy and Sell Stock solution in Python
def max_profit(prices: list[int]) -> int:
    lowest = prices[0]
    best = 0
    for price in prices:
        best = max(best, price - lowest)
        lowest = min(lowest, price)
    return best
▸Best Time to Buy and Sell Stock solution in JavaScript
function maxProfit(prices) {
  let lowest = prices[0];
  let best = 0;
  for (const price of prices) {
    best = Math.max(best, price - lowest);
    lowest = Math.min(lowest, price);
  }
  return best;
}

Common mistakes

  • Returning `max(prices) - min(prices)`, which ignores that the buy has to come before the sell.
  • Starting `best` at a negative value and returning a loss when prices only fall. The floor is 0, meaning no trade.
  • Initializing `lowest` to 0 instead of the first price (or infinity), which reports profits that were never available.
  • Resetting the best profit whenever a new minimum appears. A new minimum only affects future sells.

What interviewers look for

The key sentence is "for each sell day, the best buy day is the minimum before it." Say it, and the one-pass solution follows naturally. Interviewers also like hearing the connection to Maximum Subarray: the daily price changes form an array, and the best trade is its maximum-sum run, which is Kadane's algorithm in disguise.

Check the all-falling case out loud so it's clear you return 0 and not a negative number.

Follow-up questions

What if you can make as many trades as you like (but hold at most one share at a time)?

Add up every positive day-to-day difference, `max(0, prices[i] - prices[i - 1])`. Any rising stretch can be split into one-day trades with the same total. O(n).

What if you can make at most two trades?

Track four running values in one pass: best after the first buy, first sell, second buy, and second sell, where each builds on the previous one. That generalizes to k trades with an O(n · k) DP.

What if every sale charges a fixed fee?

With unlimited trades, keep two states: best profit while holding a share and while not holding one. On each day, `cash = max(cash, hold + price - fee)` and `hold = max(hold, cash - price)`. O(n) time, O(1) space.

Companies that ask Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock is tagged by 163 companies in our interview dataset. The score shows how often it comes up at each company.

  • Morgan Stanley100%
  • Millennium100%
  • Zoox100%
  • Tech Mahindra100%
  • Rbc100%
  • Agoda95.8%
  • Asurion94%
  • Akamai94%
  • Mastercard93.9%
  • Sigmoid91.7%
  • TSMC91%
  • Bolt90.1%
  • Duckduckgo90%
  • Zoho89.9%
  • Citadel89.9%
  • Tiger Analytics89.6%
  • Tesla89.2%
  • Garmin89.1%
  • Pagerduty88%
  • Citigroup87.1%
  • IBM86.5%
  • Toast, Inc85.2%
  • NVIDIA85%
  • Visa84.8%

and 139 more.

Practice next

  • Trapping Rain WaterHardTwo pointers with running maximums
  • Maximum SubarrayMediumKadane's algorithm
  • Coin ChangeMediumBottom-up DP over amounts
  • House RobberMedium1D dynamic programming

Get live help in the real interview

Working solutions in real time during your actual interview. Invisible to screensharing.

Start Free Trial

No credit card required

Interview Solver
  • Home
  • About
  • Pricing
  • Sign in
  • Contact
  • Blog
  • Companion
  • Mobile
  • Help Center
  • Developers
  • Use Cases
  • Software Engineer
  • Product Manager
  • Misc
  • Privacy Policy
  • Terms and Conditions
  • Refund & Cancellation
  • Discord Community
  • Affiliate Program
  • Compare
  • All Comparisons
  • vs Final Round AI
  • vs UltraCode
  • vs Interview Coder
  • vs LockedIn AI
  • vs AI Apply
  • Free Tools
  • ATS Resume Checker
  • STAR Method Builder
  • Salary Lookup
  • Big O Cheat Sheet
  • Total Comp Calculator
  • View All →
  • Interview Questions
  • Google Questions
  • Amazon Questions
  • Microsoft Questions
  • Meta Questions
  • Apple Questions
  • TikTok Questions
  • View All →
© 2026 Interview Solver, Inc. All rights reserved.