Maximizing profit for given stock quotes

后端 未结 9 1916
無奈伤痛
無奈伤痛 2020-12-07 09:45

I was asked this question while interviewing for a startup and saw this again in the recent contest at

Code Sprint:systems

**The question :

You are

9条回答
  •  心在旅途
    2020-12-07 10:23

    0.Start from end of array so that no need to recurse
    1. smax = maximum stock price from the list
    2.Then find the profit by assuming you have bought all the stocks till smax and you sell it at the price of smax

              public static void main(String[] args) {
    
              Scanner sc = new Scanner(System.in);
              int numOfTestCase = sc.nextInt();
              for (int i = 0; i < numOfTestCase; i++) {
                     int n = sc.nextInt();
                     long profit = 0;
                     int[] stockPrice = new int[n];
    
                     for (int j = 0; j < n; j++) {
                           stockPrice[j] = sc.nextInt();
                     }
    
                     int currMax = Integer.MIN_VALUE;
    
                     for (int j = n - 1; j >= 0; j--) {
                           if (currMax < stockPrice[j]) {
                                  currMax = stockPrice[j];
                           }
                           profit += (currMax - stockPrice[j]);
                     }
                     System.out.println(profit);
    
    
              }
       }
    

提交回复
热议问题