Best Time to Buy and Sell Stock in Java: The One-Pass Trick Explained
-
Last Updated: July 11, 2026
-
By: javahandson
-
Series
Learn Java in a easy way
Learn the Best Time to Buy and Sell Stock problem in Java with a brute force and a one-pass solution, a step-by-step dry run, and a beginner-friendly explanation.
The Best Time to Buy and Sell Stock problem in Java is one of those questions that looks harder than it is. You see the word “stock” and your brain jumps to charts and math. Relax. The idea behind it is simple, and you can solve it in a single pass.
Here is the task in plain words. You get a list of daily prices for one stock. You want to buy on one day and sell on a later day. Your goal is to make the biggest profit you can. If no profit is possible, you return zero.
In this guide, we start with the slow but obvious way. After that, we speed it up with a neat one-pass trick. We also dry-run the code by hand, so you can watch it work step by step. By the end, this problem will feel easy.
Let us pin down the rules first. A clear problem statement saves you from silly bugs later.
For the array above, the best move is to buy at 1 on day 1 and sell at 6 on day 4. That gives a profit of 5. Notice the buy day always comes before the sell day. You cannot travel back in time and buy after you sell.
| 💡 Interview Insight Interviewers often check if you understand the ordering rule. Say it out loud: the sell day must come after the buy day. This one line shows you grasped the core constraint before writing any code. |
The first idea most people have is simple. Try every possible buy day with every later sell day. Track the biggest profit you find along the way.
maxProfit = 0
for buy from 0 to n-1:
for sell from buy+1 to n-1:
profit = prices[sell] - prices[buy]
if profit > maxProfit:
maxProfit = profit
return maxProfitThe outer loop picks the buy day. The inner loop picks a later sell day. We compute the profit for that pair and keep the best one. We start selling at buy plus 1, so we never sell before we buy.
public class StockBrute {
public static int maxProfit(int[] prices) {
int maxProfit = 0;
for (int buy = 0; buy < prices.length; buy++) {
for (int sell = buy + 1; sell < prices.length; sell++) {
int profit = prices[sell] - prices[buy];
if (profit > maxProfit) {
maxProfit = profit;
}
}
}
return maxProfit;
}
public static void main(String[] args) {
int[] prices = { 7, 1, 5, 3, 6, 4 };
System.out.println(maxProfit(prices)); // 5
}
}Let us walk through the code slowly. Each part has a clear job.
This code is easy to read and hard to get wrong. That is its main strength. The problem is speed, which we fix next.
The brute force checks almost every pair of days. For an array of size n, that is about n^2 over two comparisons. So the time is O(n squared). The space stays O(1) because we only track a few variables. For small inputs, this is fine. For large ones, it slows down fast.
Now for the smart version. The key idea is to remember the lowest price we have seen so far. As we walk the array once, we ask a simple question each day. If I sell today, what profit do I get from the lowest price seen so far?
So we track two things. First, the minimum price up to now. Second, the highest profit so far. At each price, we update both. That single pass is all we need.
minPrice = prices[0]
maxProfit = 0
for price in prices:
if price < minPrice:
minPrice = price
else if price - minPrice > maxProfit:
maxProfit = price - minPrice
return maxProfitpublic class StockOnePass {
public static int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}
public static void main(String[] args) {
int[] prices = { 7, 1, 5, 3, 6, 4 };
System.out.println(maxProfit(prices)); // 5
}
}This version does more thinking, so let us break it down gently.
Because we only scan the array once, the work is quick. That single change is what makes this approach shine.
| 💡 Interview Insight A classic follow-up asks why the buy-and-sell logic is in an if-else rather than two separate ifs. The reason is subtle: on the day we hit a new low, selling makes no sense yet. So we skip the profit check that day and move on. |
Watching the code run by hand makes it stick. So let us trace two examples. The first one is short and gentle. The second one has a twist that many beginners miss.
We track the minimum price and the best profit as they change. Walk left to right, one day at a time.
| Day | Price | minPrice before | profit if sold today | maxProfit after |
|---|---|---|---|---|
| 0 | 7 | MAX | – | 0 |
| 1 | 1 | 7 | – | 0 |
| 2 | 5 | 1 | 5 - 1 = 4 |
4 |
| 3 | 3 | 1 | 3 - 1 = 2 |
4 |
| 4 | 6 | 1 | 6 - 1 = 5 |
5 |
| 5 | 4 | 1 | 4 - 1 = 3 |
5 |
Look at day 4 closely. The price is 6, and our lowest so far is 1. Selling now gives a profit of 5, which beats our old best of 4. So maxProfit becomes 5. On day 5, the price drops to 4, so the profit shrinks, and our best stays at 5.

The sketch above shows the same trace on paper. The price array sits on top, the buy and sell days are marked, and the running profit sits below.
This one is trickier, and that is the point. Watch what happens when a new low price shows up late in the array.
| Day | Price | minPrice before | profit if sold today | maxProfit after |
|---|---|---|---|---|
| 0 | 7 | MAX | – | 0 |
| 1 | 2 | 7 | – | 0 |
| 2 | 5 | 2 | 5 - 2 = 3 |
3 |
| 3 | 8 | 2 | 8 - 2 = 6 |
6 |
| 4 | 1 | 2 | new low, skip | 6 |
| 5 | 3 | 1 | 3 - 1 = 2 |
6 |
| 6 | 6 | 1 | 6 - 1 = 5 |
6 |
| 7 | 4 | 1 | 4 - 1 = 3 |
6 |
The best profit lands on day 3. We buy at 2 and sell at 8, so the profit is 6. Then on day 4 the price crashes to 1, a brand new low. Here is the twist. A lower buy price appears, but it comes too late to beat 6. The rest of the array never rises high enough above 1 to catch up.
This is why we track minPrice and maxProfit as two separate values. The lowest price and the best profit do not always come from the same stretch of days. In this example the best deal happened early, even though a cheaper buy price showed up later.

Compare the two examples and the idea clicks. In example 1, the low and the peak lined up nicely. In example 2, they did not, yet one simple pass still found the right answer. That is the strength of tracking both values at once.
Both approaches return the correct answer. They just pay different prices. Here is the plain comparison.
In an interview, start by mentioning the brute force. It shows you understand the problem. Then improve it with the one-pass scan to show you can optimize. That jump from slow to fast is exactly what interviewers want to see.
| 💡 Interview Insight Strong candidates point out a nice detail: unlike Two Sum, this one-pass solution needs no HashMap. It stays at O(1) space. Saying that shows you notice when a problem does not need extra memory. |
A few small traps catch beginners on this problem. Keep these in mind.
The Best Time to Buy and Sell Stock problem in Java looks like a math puzzle, but it is really a scanning trick. You keep the lowest price and the highest profit so far, all in one pass.
So take the lesson, not just the answer. Brute force first to be safe. Then reach for the one-pass scan when you need speed. Once this running-minimum pattern feels natural, many array problems get easier.
A: You are given an array of daily prices for one stock. You must buy on one day and sell on a later day to get the maximum profit. If prices only fall, the answer is 0 because no profitable trade exists.
A: The one-pass scan is fastest. You track the lowest price so far and the best profit so far as you walk the array once. This runs in O(n) time and O(1) space.
A: The brute force uses two nested loops over buy and sell days, so it runs in O(n squared) time and O(1) space. It is simple and correct, but it gets slow as the array grows.
A: On the day you hit a new lowest price, selling makes no sense yet. The if-else skips the profit check on that day and just updates the minimum, which keeps the logic correct and clean.
A: No. Unlike Two Sum, this problem needs no extra data structure. Two simple variables, the minimum price and the best profit, are enough, so the solution stays at O(1) space.
You now have the one-pass scan in your toolkit, so let us keep the momentum going. The next problem in this series builds a similar habit of tracking things as you walk through an array.