Ecommet

Best Time to Buy and Sell Stock

Easy Problem 4 of 151 Java and Python

Problem

You are given an array prices where prices[i] is the price of a stock on day i.

Choose one day to buy and a later day to sell. Return the maximum profit you can make. If no profit is possible, return 0.

Example 1

Input
prices = [7, 1, 5, 3, 6, 4]
Output
5
Why
Buy on day 1 at price 1 and sell on day 4 at price 6.

Example 2

Input
prices = [7, 6, 4, 3, 1]
Output
0
Why
The price only falls, so there is no profitable trade.

Constraints

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴

Explanation

If you sell on day i, the best day to have bought is the cheapest day before i. So you never need to look back over the whole array: keep the minimum price so far and the best profit so far.

Approach 1 · Naive

Try every buy and sell day

  • Time O(n²)
  • Space O(1)

For each buy day, try every later sell day and keep the largest difference.

  1. For every i, for every j > i, compute prices[j] - prices[i].
  2. Keep the maximum, starting from 0.
Java
class Solution {
    public int maxProfit(int[] prices) {
        int best = 0;
        for (int i = 0; i < prices.length; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                best = Math.max(best, prices[j] - prices[i]);
            }
        }
        return best;
    }
}
Python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        best = 0
        for i in range(len(prices)):
            for j in range(i + 1, len(prices)):
                best = max(best, prices[j] - prices[i])
        return best

Approach 2 · Optimal

Track the lowest price

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

Scan once. At each day, the best sale today is price - lowest price so far. Update the answer, then update the lowest price.

  1. Set low to the first price and best to 0.
  2. For each price: best = max(best, price - low), then low = min(low, price).
  3. Return best.
Java
class Solution {
    public int maxProfit(int[] prices) {
        int low = prices[0];
        int best = 0;
        for (int price : prices) {
            best = Math.max(best, price - low);
            low = Math.min(low, price);
        }
        return best;
    }
}
Python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        low = prices[0]
        best = 0
        for price in prices:
            best = max(best, price - low)
            low = min(low, price)
        return best

Complexity compared

ApproachTimeSpace
Naive Try every buy and sell dayO(n²)O(1)
Optimal Track the lowest priceO(n)O(1)

Key takeaways

  • "Best pair where one comes after the other" usually means carrying the best value from the left as you scan.
  • This is the simplest form of dynamic programming: one number of state per step.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem