The 30 second answer
I scan prices once while tracking the lowest price so far. At each day the best profit if I sell today is price minus that minimum, and I keep the maximum of those. If prices only go down, the answer stays zero because I am allowed not to trade. That is linear time and constant space.
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. Original: LeetCode 121: Best Time to Buy and Sell Stock.
Understanding the prompt There is exactly one transaction, the sell must come after the buy, and "no profit" means returning 0, not a negative number.
Pattern recognition The answer at day i depends only on the minimum before i. That is a running-state single pass.
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).
Alternatives Kadane on the daily differences: the maximum subarray sum of price[i] - price[i-1] gives the same answer.
Java solution
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
}
}Complexity O(n) time and O(1) space.
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.
Tests [7,1,5,3,6,4] returns 5. [7,6,4,3,1] returns 0. [5] returns 0.
How to say it in the interview "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."
Sources (2)
- LeetCode 121: Best Time to Buy and Sell Stockleetcode.com
- Java SE 17 API: Mathdocs.oracle.com