Best Time to Buy and Sell Stock in Java: The One-Pass Trick Explained

  • Last Updated: July 11, 2026
  • By: javahandson
  • Series
img

Best Time to Buy and Sell Stock in Java: The One-Pass Trick Explained

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.

1. Introduction

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.

2. Understanding the Problem

Let us pin down the rules first. A clear problem statement saves you from silly bugs later.

  • You get an array of prices, for example, [7, 1, 5, 3, 6, 4].
  • Each spot in the array is the price on that day.
  • You must buy first, then sell on a later day.
  • You want the maximum profit, which is the sell price minus the buy price.
  • If prices only fall, there is no profit, so you return 0.

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.

3. Approach 1: Brute Force

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.

3.1 Pseudocode

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 maxProfit

The 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.

3.2 Java Code

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
    }
}

3.3 Why This Works, Step by Step

Let us walk through the code slowly. Each part has a clear job.

  • The variable maxProfit starts at 0, which covers the no-profit case.
  • The outer loop variable buy points to the day we buy.
  • The inner loop variable sells points to a later day we might sell on.
  • Inside, we compute profit and compare it with our best so far.
  • If this pair beats the record, we update maxProfit.

This code is easy to read and hard to get wrong. That is its main strength. The problem is speed, which we fix next.

3.4 Time and Space Cost

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.

4. Approach 2: The One-Pass Trick

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.

4.1 Pseudocode

minPrice = prices[0]
maxProfit = 0
for price in prices:
    if price < minPrice:
        minPrice = price
    else if price - minPrice > maxProfit:
        maxProfit = price - minPrice
return maxProfit

4.2 Java Code

public 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
    }
}

4.3 Reading the Code Line by Line

This version does more thinking, so let us break it down gently.

  • We set minPrice to a very large value at the start, so the first real price beats it.
  • We set maxProfit to 0, which handles the case where prices only fall.
  • We loop once through the array. There is no inner loop here, which is the whole point.
  • If today’s price is lower than our minimum, we update the minimum.
  • Otherwise, we check if selling today beats our best profit, and update if it does.

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.

5. Dry Run of the One-Pass Approach

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.

5.1 Example 1: prices = [7, 1, 5, 3, 6, 4]

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.

Best Time to Buy and Sell Stock

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.

5.2 Example 2: prices = [7, 2, 5, 8, 1, 3, 6, 4]

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.

Best Time to Buy and Sell Stock dsa

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.

6. Brute Force vs One-Pass

Both approaches return the correct answer. They just pay different prices. Here is the plain comparison.

  • Brute force runs in O(n squared) time and O(1) space. It is simple but slow on big inputs.
  • One-pass runs in O(n) time and O(1) space. It is faster and uses no extra memory.

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.

7. Common Mistakes and Edge Cases

A few small traps catch beginners on this problem. Keep these in mind.

  • Do not sell before you buy. The buy day must always come first.
  • Return 0 when prices only fall. There is no valid profit to make.
  • An array with one price gives 0, because you cannot sell on a later day.
  • Watch the if-else. Using two separate ifs can pick the wrong minimum on some inputs.

8. Conclusion

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.

9. Interview Questions

Q: What is the Best Time to Buy and Sell Stock problem in Java?

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.

Q: What is the fastest way to solve Best Time to Buy and Sell Stock in Java?

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.

Q: What is the time complexity of the brute force stock solution?

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.

Q: Why does the one-pass solution use an if-else instead of two ifs?

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.

Q: Does this problem need a HashMap like Two Sum?

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.

10. What’s Next

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.

  • Next up: Contains Duplicate. You check whether any value appears more than once, often using a HashSet in a single pass.

11. Further Reading

 

Leave a Comment