Problem
Section titled “Problem”You are given an array prices where prices[i] is the price of a given stock on the ith 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.
Example 1:
Input: prices = [7,1,5,3,6,4]Output: 5Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.Example 2:
Input: prices = [7,6,4,3,1]Output: 0Explanation: In this case, no transactions are done and the max profit = 0.Constraints:
-
prices.length -
prices[i]
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Trying every pair (buy day, sell day) is . Look at it from the sell side instead: if we sell on day i, the best possible buy day is the cheapest day before i. So while scanning left to right we only need to remember one number, minPrice, the lowest price seen so far. The profit from selling today is price - minPrice, and the answer is the best of these over all days.
Updating minPrice after computing today’s profit is not even necessary for correctness: if today is the new minimum, its profit is 0 (buying and selling on the same day), which never beats best.
Algorithm
Section titled “Algorithm”- Set
minPrice = INT_MAXandbest = 0. - For each
priceinprices:minPrice = min(minPrice, price);best = max(best, price - minPrice).
- Return
best.
On Example 1, minPrice becomes 7, then 1, and stays 1; the profits after that are 4, 2, 5, 3, so best = 5 (buy at 1, sell at 6).
Complexity
Section titled “Complexity”- Time: — one pass over
prices. - Space: — two variables.
Edge cases
Section titled “Edge cases”- Falling prices (Example 2): every day is a new minimum, every profit is
0, and the answer is0. - Single day: the only profit is
price - price = 0.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: int maxProfit(vector<int>& prices) { int minPrice = INT_MAX, best = 0; for (int price : prices) { minPrice = min(minPrice, price); best = max(best, price - minPrice); } return best; }};class Solution { public int maxProfit(int[] prices) { int minPrice = Integer.MAX_VALUE, best = 0; for (int price : prices) { minPrice = Math.min(minPrice, price); best = Math.max(best, price - minPrice); } return best; }}class Solution: def maxProfit(self, prices: list[int]) -> int: min_price, best = float('inf'), 0 for price in prices: min_price = min(min_price, price) best = max(best, price - min_price) return bestGive it a try first
Attempt the problem on LeetCode — the code will still be here.