Advertisement
amitsen01ei

Untitled

Aug 7th, 2023 (edited)
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.02 KB | Source Code | 0 0
  1. public class MaximumStockProfit {
  2.  
  3.     /**
  4.      * Returns the maximum profit possible from an array of stock prices
  5.      * where the index represents the day and value represents the price
  6.      * of the stock that day. The time complexity of the following solution
  7.      * would be O(N) and space complexity would be O(1). Requires Java 10+
  8.      * @param stockPrices an array of stock prices
  9.      * @return maximum profit possible. If not profit is possible, returns 0.
  10.      */
  11.     public static int findMaximumStockProfit (int[] stockPrices) {
  12.  
  13.         if (stockPrices.length < 2) {
  14.             return 0;
  15.         }
  16.  
  17.         int lowestStockPrice = stockPrices[0];
  18.         int maxProfit = 0;
  19.  
  20.         for (var i = 1; i < stockPrices.length; i++) {
  21.  
  22.             if (stockPrices[i] < lowestStockPrice) {
  23.                 lowestStockPrice = stockPrices[i];
  24.             } else {
  25.                 maxProfit = Math.max(maxProfit, stockPrices[i] - lowestStockPrice);
  26.             }
  27.         }
  28.  
  29.         return maxProfit;
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement