Maximum difference between two elements such that larger element appears after the smaller number | 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 ; Initialize Result ; Initialize max element from right side ; Driver Code ; Function calling
function maxDiff ( arr , n ) { let maxDiff = - 1 ; let maxRight = arr [ n - 1 ] ; for ( let i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > maxRight ) maxRight = arr [ i ] ; else { let diff = maxRight - arr [ i ] ; if ( diff > maxDiff ) { maxDiff = diff ; } } } return maxDiff ; } let arr = [ 1 , 2 , 90 , 10 , 110 ] ; let n = arr . length ; document . write ( " " + maxDiff ( arr , n ) ) ;