Advertisement
zoltanvi

Apple Stocks problem INTERVIEW QUESTION

Jul 14th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1. // https://www.interviewcake.com/question/java/stock-price
  2.  
  3. public class Main{
  4.    
  5.     public static void main(String[] args) {
  6.         int[] prices = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
  7.         System.out.println(getMaxProfit(prices));
  8.  
  9.     }
  10.  
  11.     public static int getMaxProfit(int[] stockPrices){
  12.         int maxProfit = 0;
  13.         if(stockPrices.length <= 1){
  14.             throw new IllegalArgumentException();
  15.         }
  16.  
  17.         int min = Integer.MAX_VALUE;
  18.         int max = Integer.MIN_VALUE;
  19.  
  20.         int i = 0;
  21.         int j = stockPrices.length - 1;
  22.        
  23.         while(i < j){
  24.             if(stockPrices[i] < min){
  25.                 min = stockPrices[i];
  26.             }
  27.             if(stockPrices[j] > max){
  28.                 max = stockPrices[j];
  29.             }
  30.             i++;
  31.             j--;
  32.         }
  33.         maxProfit = max - min;
  34.         return maxProfit;
  35.     }
  36.    
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement