A integer array is given as input. find the difference between each element. Return the index of the largest element which has the largest difference gap.
input: {2,3,4,2,3}
logic: 2-3=1,3-4=1,4-2=2,2-3=1
2 is the max diff between 4 and 2,return the index of 4(2)
output:2
package com.example;// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number import java.io.*; class GFG { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ static int maxDiff(int arr[], int n) { // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } /* Driver program to test above function */ public static void main (String[] args) { int arr[] = {2,3,4,2,3}; int n = arr.length; // Function calling System.out.println ("Maximum difference is " + maxDiff(arr, n)); } //This code is contributed by Tushil.. }