Best Time to Buy and Sell Stock

Easy ArrayGreedy

Problem

Given an array prices where prices[i] is the stock price on day i, find the maximum profit from one buy and one later sell. Return 0 if no profit is possible.

Example 1 Input: prices = [7,1,5,3,6,4] Output: 5 Explain: Buy at 1 (day 1), sell at 6 (day 4).
Example 2 Input: prices = [7,6,4,3,1] Output: 0 Explain: Prices only decrease — no profit.

Constraints

Approach — Greedy

This is a Greedy problem. The idea: make the locally best choice at each step, which provably builds up to the global optimum here. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n log n) time.

Solution code

Python

class Solution:
    def maxProfit(self, prices):
        low = float('inf')
        best = 0
        for p in prices:
            low = min(low, p)
            best = max(best, p - low)
        return best

Java

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int price : prices) {
            if (price < minPrice) {
                minPrice = price;
            } else {
                maxProfit = Math.max(maxProfit, price - minPrice);
            }
        }
        return maxProfit;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Best Time to Buy and Sell Stock interactively → ← All solutions