Buy and sell stock is one of the friendliest array problems, because you only need to remember one number while you walk the list. Welcome back to the Tekraze DSA series. Yesterday we solved Two Sum in Java, Python and Rust with a hash map. Today we stay with arrays and learn a trick that is even lighter on memory.
Also Read: Missed the first problem? DSA Series Day 1: Two Sum in Java, Python and Rust
What Is the Best Time to Buy and Sell Stock Problem?
You get an array prices where prices[i] is the price of a stock on day i. You may buy once and sell once, and you must buy before you sell. Return the maximum profit. If no profit is possible, return 0. This is the classic Best Time to Buy and Sell Stock problem on LeetCode.
text
Input: prices = [7, 1, 5, 3, 6, 4] Output: 5 Why: buy at 1 (day 1), sell at 6 (day 4), profit = 6 - 1 = 5 Input: prices = [7, 6, 4, 3, 1] Output: 0 Why: prices only fall, so you never buy
How Should You Think About It in Plain Words?
Pretend you are travelling through time, one day at a time. Every day you ask one thing: if I sell today, what is the cheapest day I could have bought on before now?
You don’t need to remember every past price. You only need the lowest one so far. So you carry two numbers in your head: the cheapest price you have seen, and the best profit you have found. That’s the whole solution.

What Does the Brute Force Way to Buy and Sell Stock Look Like?
The first honest idea is to try every buy day with every later sell day and keep the biggest difference.
python
def max_profit_brute(prices):
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
Time is O(n²) because every pair of days gets checked, which is why this buy and sell stock approach slows down fast. Space is O(1). Picture one year of minute by minute prices. That is 525,600 values, which means roughly 138 billion pair checks. Let’s do better.

How Do We Get the Optimal O(n) Solution?
Walk the array once. The one pass buy and sell stock idea fits in a sentence: if today’s price is lower than your minimum, it becomes the new minimum, because it is a better day to buy. Otherwise, check what you would earn by selling today and keep the best result.
Time is O(n), one pass. Space is O(1), just two variables. If you want to see how these numbers are worked out, read our time and space complexity explained simply post.

Java solution to buy and sell stock
java
public class Solution {
public static int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int best = 0;
for (int p : prices) {
if (p < minPrice) minPrice = p;
else best = Math.max(best, p - minPrice);
}
return best;
}
public static void main(String[] args) {
int[][] tests = {{7, 1, 5, 3, 6, 4}, {7, 6, 4, 3, 1}, {2, 4, 1}, {5}};
int[] expected = {5, 0, 2, 0};
for (int i = 0; i < tests.length; i++) {
int got = maxProfit(tests[i]);
System.out.println("Test " + (i + 1) + ": " + got + (got == expected[i] ? " PASS" : " FAIL"));
}
}
}
Java’s Math.max keeps the running best, and Integer.MAX_VALUE makes sure the first price always becomes the minimum.
Python solution
python
def max_profit(prices):
min_price = float("inf")
best = 0
for p in prices:
if p < min_price:
min_price = p
else:
best = max(best, p - min_price)
return best
if __name__ == "__main__":
tests = [([7, 1, 5, 3, 6, 4], 5), ([7, 6, 4, 3, 1], 0), ([2, 4, 1], 2), ([5], 0)]
for i, (prices, want) in enumerate(tests, 1):
got = max_profit(prices)
print(f"Test {i}: {got} {'PASS' if got == want else 'FAIL'}")
Rust solution
rust
fn max_profit(prices: &[i32]) -> i32 {
let mut min_price = i32::MAX;
let mut best = 0;
for &p in prices {
if p < min_price {
min_price = p;
} else {
best = best.max(p - min_price);
}
}
best
}
fn main() {
let tests: [(&[i32], i32); 4] = [
(&[7, 1, 5, 3, 6, 4], 5),
(&[7, 6, 4, 3, 1], 0),
(&[2, 4, 1], 2),
(&[5], 0),
];
for (i, (prices, want)) in tests.iter().enumerate() {
let got = max_profit(prices);
println!("Test {}: {} {}", i + 1, got, if got == *want { "PASS" } else { "FAIL" });
}
}
In Rust we take a slice &[i32], so the function borrows the prices without copying them. The Rust standard library docs on slices explain this in more detail. All three programs use the same four tests: a normal case, falling prices, a dip after the peak like [2, 4, 1], and a single day.
What Are the Tips and Tricks for an Easy Solution?
These habits work for any buy and sell stock variant you meet later.
- Think one pass. When a problem asks for the best pair where order matters, ask what you need to remember from the past. Usually it’s a single running value.
- Track the minimum, not the pair. Profit today is price minus the cheapest earlier price. That turns two loops into one.
- Start best at 0. This handles the no profit case for free, so you never return a negative number.
- Mind the update order. Compare first, then update the minimum, or use an if else like we did. Either way you never sell on the same day you buy.
- Remember the Kadane link. This is the same idea as the maximum subarray problem on daily price changes. It comes back on the DP days.
- Explain it in interviews. Say the brute force, give O(n²), then explain that you only need the minimum so far. Interviewers like hearing the reason behind the optimisation.
What Are the Common Mistakes When You Buy and Sell Stock in Code?
- Returning max minus min of the whole array. That ignores the rule that you must buy before you sell, and
[2, 4, 1]breaks it. - Returning a negative profit instead of 0 when prices only fall.
- Starting the minimum at 0 instead of a very large value or the first price.
- Mixing this up with the multiple transactions version, which has a different, greedy answer.
Where Is This Pattern Used in the Real World?
Trading dashboards and crypto bots use this buy and sell stock idea to show the best entry and exit in a price window. Backtesting tools run it to measure the maximum gain or the maximum drawdown of a strategy. The same running minimum idea shows up in monitoring too, like finding the biggest jump in latency or temperature after a low point.
This is a learning exercise, not trading advice. Real markets have fees, slippage and no way to see tomorrow’s price.
What Comes Next in the Series?
Tomorrow we continue with arrays and hashing. Before then, try solving the buy and sell stock problem again without looking. Then try the variant where you can buy and sell many times.
Frequently Asked Questions
Why is the one pass solution O(1) space?
It only stores two numbers, the lowest price so far and the best profit so far, no matter how long the array is.
What should I return if prices only go down?
Return 0. You simply don’t make a trade, and starting the best profit at 0 handles this automatically.
Why not just subtract the minimum from the maximum to buy and sell stock?
The maximum may come before the minimum. You must buy before you sell, so you need the lowest price before each sell day.
Is the buy and sell stock problem related to Kadane’s algorithm?
Yes. If you turn prices into daily changes, the best profit is the maximum subarray sum of those changes.
Do interviews still ask the buy and sell stock problem?
It is a very common easy array question, and it leads into harder versions with multiple trades, cooldowns and fees.





