Quick actions

cmd+k|ctrl+k

Navigation

Languages

Max profit from buying and selling stocks once

Snippet info

Language

Java

Visibility

public

Author

shraddharao-

Created

2024-02-27T20:27:16.551184Z

Updated

2024-02-27T20:27:16.551184Z

class Main {
    /*
    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.
    prices = [7, 1, 5, 3, 6, 4]
    output --> 5

    */
    
    // conditonal - if less than 2 days then no profit
    // min price --> first day, max price =0
    // iterate prices array frpm 2day
    // update min price so far
    //calculate profiy sold on current day
    // calculatye max profit on current day is more then return max profit
    
    public static int maxProfit(int[] prices){
        if(prices == null || prices.length < 2){
            return 0;
        }
        
        int minPrice = prices[0];
        int maxPrice = 0;
        
        for(int i =1; i<prices.length; i++){
            minPrice = Math.min(minPrice, prices[i]);
            int profit = prices[i] - minPrice;
            
            maxPrice= Math.max(maxPrice, profit);
        }
        
        return maxPrice;
    }
    
    public static void main(String[] args) {
        int[] prices = {7,1,5,3,6,4};
        int result = maxProfit(prices);
        System.out.println(result);
    }
}
INFO