leetcode

Best Time to Buy and Sell Stock - Link

Question Description

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.


Constraints


Brute Force

Approach

The brute force approach involves checking all possible pairs of buy and sell days. For each pair (i, j) where i < j, calculate the profit as prices[j] - prices[i] and keep track of the maximum profit.

This approach has a time complexity of O(n²) due to the nested loops, which is inefficient for large inputs.

Dry Run

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

Final Answer = 5

Solution

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        for (int i = 0; i < prices.length; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                int diff = prices[j] - prices[i];
                max = Math.max(diff, max);
            }
        }
        return max;
    }
}

Time Complexity

O(n²)


Optimized Solution

Approach

The optimized solution uses a single pass through the array. We keep track of the minimum price seen so far (buy) and the maximum profit achievable. For each day, if the current price is less than the buy price, update buy. Otherwise, calculate the profit and update max if it’s greater.

Dry Run

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

Final Answer = 5

Solution

class Solution {
    public int maxProfit(int[] prices) {
        int buy = prices[0];
        int max = 0;

        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < buy) buy = prices[i];
            else if (prices[i] - buy > max) max = prices[i] - buy;
        }
        return max;
    }
}

Time and Space Complexity