2018-04-24

Write a program to find maximum profit


  1. public class MaxProfit {
  2.   public static void main(final String[] args) {
  3.     int a[] = { 4, 1, 10, 2, 3, 5, 6, 25, 48, 8, 26 };
  4.     int max = a[a.length - 1];
  5.     int min = a[a.length - 1];
  6.     int indexOfMax = a.length - 1;
  7.     int indexOfMin = a.length - 1;
  8.     int dif = -1;
  9.     for (int i = a.length - 2; i >= 0; i--) {
  10.       if (max < a[i]) {
  11.         max = a[i];
  12.         indexOfMax = i;
  13.       }
  14.       if (max > a[i]) {
  15.         min = a[i];
  16.         indexOfMin = i;
  17.       }
  18.       if ((indexOfMax > indexOfMin)) {
  19.         if (dif < (max - min)) {
  20.           dif = max - min;
  21.         }
  22.       }
  23.     }
  24.     System.out.println(dif);
  25.   }
  26. }

1 comment:

  1. Hi Geeks !!
    Great job you have done here. This is one of the top most interview question asked to me by an interviewer. I hope this will help to other geeks as well who give an interview.

    ReplyDelete