PPractick

DSA interview question

Best Time to Buy and Sell Stock

Medium · Algorithms · Topics: dynamic programming, array

The problem

This is the foundational version of your trading bot backend, before any of the fee/cooldown/k-transaction rules existed. Given an array prices where prices[i] is the stock price on day i, you're allowed to complete at most one transaction (buy on one day, sell on a later day). Return the maximum profit you can achieve. If no profit is possible, return 0.

Function signature

int maxProfit(vector<int>& prices);

Test cases

Input pricesOutputExplanation
[7,1,5,3,6,4]5Buy@1, sell@6 → profit 5
[7,6,4,3,1]0Strictly decreasing — no profitable trade, return 0
[1,2,3,4,5]4Buy@1, sell@5 → profit 4
[1]0Single day — no transaction possible
[]0Empty array
[2,4,1]2Buy@2, sell@4 → profit 2 (buying at 1 comes too late to sell higher)
[3,3,3,3]0No price movement — no profit possible

(Always check: you must buy before you sell — selling can never happen on an earlier or same day as buying.)

How interviewers phrase it

Clarifying questions to ask

  1. Can I choose not to transact at all if no profitable trade exists? (i.e., is 0 a valid answer?)
  2. Must I sell on a strictly later day than I buy (no same-day buy-sell)?
  3. Are prices guaranteed non-negative integers?
  4. What's the expected size of prices? (Confirms O(n) is expected over O(n²) brute force.)
  5. Can the array be empty or have just one element — what should I return then?

Follow-ups to expect

  1. "Can you do this in O(n) instead of O(n²)?"
  2. "What if you could do unlimited transactions instead of just one?"
  3. "What if you could do at most two transactions?"
  4. "What if you could do at most k transactions?"
  5. "What if there's a transaction fee or cooldown?"
  6. "Can you also return the actual buy/sell days, not just the profit?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in