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. }

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation