Best Time To Buy and Sell Stock In Java

Best Time To Buy And Sell Stock

Objective:

You are given an array of stock prices, where each element represents the price of a stock on a specific day.
Your task is to determine the maximum profit you can make by choosing a single day to buy and a different future day to sell the stock.

⚠️ You must buy before you sell, and you’re only allowed to make one transaction (i.e., buy one and sell one share).

If no profitable transaction is possible, return 0

Best Time To Buy And Sell Stock

 

Optimum Solution:

Best Time To Buy and Sell Stock Solution

 


class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;

        for (int price : prices) {
            // Track the lowest price so far
            if (price < minPrice) {
                minPrice = price;
            }
            // Calculate the profit if we sold today
            else if (price - minPrice > maxProfit) {
                maxProfit = price - minPrice;
            }
        }

        return maxProfit;
    }
}


class Solution {
    public int maxProfit(int[] prices) {
        int buyPrice = prices[0];
        int profit = 0;

        for (int i = 1; i < prices.length; i++) {
            if (buyPrice > prices[i]) {
                buyPrice = prices[i];
            }

            profit = Math.max(profit, prices[i] - buyPrice);
        }

        return profit;        
    }
}

✅ Explanation:

int minPrice = Integer.MAX_VALUE;
Here, after initialising the Integer.MAx_VALUE is : 2147483647

✅ Why Not 0?

🔴 Problem:

  • If you initialize minPrice = 0, you’re saying “I already have the lowest price possible”.

  • But stock prices can’t be negative, so due to this we are not go with ‘0’.

✅ Why Not prices[0]?

int minPrice = prices[0];
 

🟡 It’s okay — but less flexible.

This works and is a valid solution. However:

  • If you write a function that assumes the array is non-empty, it’s fine.

  • But using Integer.MAX_VALUE gives safety and clarity — especially in interviews or when refactoring code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top