Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MaximumStockProfit {
- /**
- * Returns the maximum profit possible from an array of stock prices
- * where the index represents the day and value represents the price
- * of the stock that day. The time complexity of the following solution
- * would be O(N) and space complexity would be O(1). Requires Java 10+
- * @param stockPrices an array of stock prices
- * @return maximum profit possible. If not profit is possible, returns 0.
- */
- public static int findMaximumStockProfit (int[] stockPrices) {
- if (stockPrices.length < 2) {
- return 0;
- }
- int lowestStockPrice = stockPrices[0];
- int maxProfit = 0;
- for (var i = 1; i < stockPrices.length; i++) {
- if (stockPrices[i] < lowestStockPrice) {
- lowestStockPrice = stockPrices[i];
- } else {
- maxProfit = Math.max(maxProfit, stockPrices[i] - lowestStockPrice);
- }
- }
- return maxProfit;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement