Best Time Buy Sell
Python data engineering interview problem. Difficulty: beginner. Pattern: Arrays. About 10 minutes. Free to practice.
Max profit from one buy and one later sell. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
You are given the price of a stock for each day, in order. You may buy the stock once on 1 day, and sell it once on a later day. You want to make as much profit as possible. Write a function max_profit(prices) that returns the biggest profit you can make with one buy and one sell, where the sell day must come after the buy day. If you cannot make any profit, return 0. For [7, 1, 5, 3, 6, 4] the best plan is to buy at 1 (day 2) and sell at 6 (day 5), for a profit of 5. Keep the print lines in the editor.
Requirements
- Return the largest value of sell price - buy price, where the sell day is after the buy day.
- Return 0 if no profit is possible.
- Make only one buy and one sell.
Constraints
- You must buy before you sell. You cannot sell on a day earlier than the day you bought.
- If prices only go down, the answer is 0, not a negative number.
Examples
Input: max_profit([7, 1, 5, 3, 6, 4]) Output: 5 Buy at 1, sell at 6.
Topics: lakebench, python, profit, scan.
More Python interview questions · All interview problems · Learn data engineering
Best Time Buy Sell
Interview-style drill: Max profit from one buy and one later sell.
Implement `max_profit(prices: list) -> int` for one transaction. Example: `[7, 1, 5, 3, 6, 4]` → `5` (buy 1, sell 6). Keep the harness.