Quick actions

cmd+k|ctrl+k

Navigation

Languages

Max profit from buying and selling stocks

Snippet info

Language

Java

Visibility

public

Author

shraddharao-

Created

2024-02-27T20:09:07.571066Z

Updated

2024-02-27T20:09:19.169019Z

class Main {
    /*
    Given an integer array prices where prices[i] is the price of a given stock
    on the ith day, find and return the maximum profit you can achieve by 
    buying and selling the stock. 
    You can only hold at most one share of the stock at any time,
    but you can buy and sell multiple times on the same day.
    
    input --> prices = [7, 1, 5, 3, 6, 4]
    output --> 7

    Time Complexity:O(n), Space Complexity: O(1)
    */
    
    // create a variable where max profit starts from 0
    // itearte over the given array to check if the price of stock today is higher than yesturday
   
   public static int maxProfit(int[] prices){
       int maxProfit = 0;
       
       // loop
       for(int i=1; i<prices.length; i++){
           if (prices[i] > prices[i-1]){
               maxProfit += prices[i] - prices[i-1];
           }
       }
       return maxProfit;
   }
   
   
    public static void main(String[] args) {
        int[] prices = {1,1,5,3,6,4};
        int result = maxProfit(prices);
        System.out.print(result);
    }
}
INFO