fork download
  1. class FindMaxProfit
  2. {
  3. public static void main(String[] args)
  4. {
  5. int arr[] = {100, 80, 260, 310, 40, 535, 695};
  6. printMaxProfitPairs(arr);
  7.  
  8. int[] anotherArr = {23, 13, 25 ,29 ,33 ,19 ,34, 45, 65, 67};
  9. printMaxProfitPairs(anotherArr);
  10.  
  11. }
  12.  
  13. private static void printMaxProfitPairs(int[] arr)
  14. {
  15. final int length = arr.length;
  16. if (length <= 1)
  17. {
  18. System.out.println("Not enough elements to process");
  19. return;
  20. }
  21.  
  22. int totalProfit =0 ;
  23. for (int i = 0; i < length; )
  24. {
  25. int maxSoFar = arr[i];
  26. int min = arr[i];
  27. while (++i < length && arr[i] > maxSoFar){
  28. maxSoFar =arr[i];
  29. }
  30.  
  31. totalProfit += (maxSoFar - min);
  32. System.out.println("Max profit by buying at : " +
  33. min + " And selling at : " + maxSoFar);
  34. }
  35. System.out.println("Total profit :"+totalProfit);
  36. }
  37. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
Max profit by buying at : 100 And selling at : 100
Max profit by buying at : 80 And selling at : 310
Max profit by buying at : 40 And selling at : 695
Total profit :885
Max profit by buying at : 23 And selling at : 23
Max profit by buying at : 13 And selling at : 33
Max profit by buying at : 19 And selling at : 67
Total profit :68