Problem
Given daily prices, choose one day to buy and a later day to sell to maximise profit, or return 0 if no profit is possible.
Examples
Example 1
`prices = [7, 1, 5, 3, 6, 4]``5`Example 2
`prices = [7, 6, 4, 3, 1]``0`Example 3
`prices = [5]``0`Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
Hints
Hint 1
There is exactly one transaction, the sell must come after the buy, and "no profit" means returning 0, not a negative number.
Hint 2
The answer at day i depends only on the minimum before i. That is a running-state single pass.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Try every buy and sell pair: O(n²).
Optimal. Keep minPrice and best. For each price, update best = max(best, price - minPrice) and then minPrice = min(minPrice, price).
Alternative. Kadane on the daily differences: the maximum subarray sum of price[i] - price[i-1] gives the same answer.
Complexity
- Time
- O(n)
O(n) time and O(1) space.
- Space
- O(1)
Code
public class BestTimeStock {
static int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int best = 0;
for (int p : prices) {
best = Math.max(best, p - minPrice);
minPrice = Math.min(minPrice, p);
}
return best;
}
public static void main(String[] args) {
System.out.println(maxProfit(new int[] {7, 1, 5, 3, 6, 4})); // 5
System.out.println(maxProfit(new int[] {7, 6, 4, 3, 1})); // 0
System.out.println(maxProfit(new int[] {5})); // 0
}
}Edge cases
- A single day returns 0.
- Strictly falling prices return 0.
- The first subtraction uses Integer.MAX_VALUE:
p - MAX_VALUEis a large negative number that doesn't overflow for non-negative prices, andmaxwith 0 discards it.
Follow-ups
- Unlimited transactions (LeetCode 122): sum every positive daily gain.
- Cooldown or fee: state-machine DP.
Interview script
"For each day, the best sale is today's price minus the cheapest price before it. So I keep a running minimum and a running best profit. One pass, O(1) space, and it returns 0 if prices only fall."
Source: LeetCode 121: Best Time to Buy and Sell Stock Source: Java SE 17 API: Math
Sources (2)
- LeetCode 121: Best Time to Buy and Sell Stockleetcode.com
- Java SE 17 API: Mathdocs.oracle.com