EvalFrame Technical Mock Interviews & Coding Practice

Best Time to Buy and Sell Stock

Easy · Greedy / Array · Algorithm problem · all problems

You are given an array `prices` where `prices[i]` is the price of a given stock on the `i`-th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. **Examples:** ```typescript maxProfit([7, 1, 5, 3, 6, 4]) // 5 (Buy day 2 at 1, sell day 5 at 6) maxProfit([7, 6, 4, 3, 1]) // 0 (No profitable transactions) ```

Solve It in the BrowserPractice Explaining It Out Loud

Optimal Approach

  • Time complexity: O(n)
  • Space complexity: O(1)

We only scan the prices array once in a single pass of length n. Tracking the minimum price seen so far and updating profit takes constant operations, yielding O(n) linear time.

Follow-Up Questions Interviewers Ask About Best Time to Buy and Sell Stock

  • What if you could buy and sell as many times as you like (Best Time to Buy and Sell Stock II)?
    You can use a greedy approach: whenever prices[i] > prices[i-1], add the difference (prices[i] - prices[i-1]) to total profit. You capture every upward price slope.
  • What if you are allowed at most two transactions (Best Time to Buy and Sell Stock III)?
    Use dynamic programming with four state variables (firstBuy, firstProfit, secondBuy, secondProfit) tracking optimal profits after each action in a single O(n) pass.
  • How does this problem relate to the Maximum Subarray problem (Kadane’s Algorithm)?
    If you convert the prices array into daily differences (price[i] - price[i-1]), finding the maximum profit for a single buy-sell transaction is mathematically identical to finding the maximum contiguous subarray sum.

Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.