Advertisement
amitsen01ei

StockProfitMax.java

Nov 6th, 2023
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | Source Code | 0 0
  1. public class Solution {
  2.  
  3.     /**
  4.      * Calculates the maximum profit from stock trading with the constraint of
  5.      * holding at most one share of stock at a time, but allows buying and selling
  6.      * on the same day.
  7.      *
  8.      * @param prices Array of stock prices where prices[i] is the price of the stock on the ith day.
  9.      * @return The maximum profit that can be achieved.
  10.      *
  11.      * Time Complexity: O(n), where n is the length of the prices array.
  12.      *                  This is because we need to traverse the entire array once.
  13.      * Space Complexity: O(1), as the solution requires a constant amount of space
  14.      *                   for the variables used, regardless of the input size.
  15.      */
  16.     private static int maxProfit(int[] stockPrices) {
  17.         if (stockPrices == null || stockPrices.length <= 1) {
  18.             return 0;
  19.         }
  20.  
  21.         var maxProfit = 0;
  22.         for (var i = 1; i < stockPrices.length; i++) {
  23.             if (stockPrices[i] > stockPrices[i - 1]) {
  24.                 maxProfit += stockPrices[i] - stockPrices[i - 1];
  25.             }
  26.         }
  27.  
  28.         return maxProfit;
  29.     }
  30.  
  31.     public static void main(String[] args) {
  32.         var stockPricesT1 = new int[] {7, 1, 5, 3, 6, 4};
  33.         System.out.println("Maximum profit: " + maxProfit(stockPricesT1));
  34.  
  35.         var stockPricesT2 = new int[] {1, 2, 3, 4, 5};
  36.         System.out.println("Maximum profit for example 2: " + maxProfit(stockPricesT2));
  37.  
  38.         var stockPricesT3 = new int[] {7, 6, 4, 3, 1};
  39.         System.out.println("Maximum profit for example 3: " + maxProfit(stockPricesT3));
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement