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 diff , current sum and max sum ; Calculate current diff ; Calculate current sum ; Update max sum , if needed ; Driver Code ; Function calling
function maxDiff ( arr , n ) { let diff = arr [ 1 ] - arr [ 0 ] ; let curr_sum = diff ; let max_sum = curr_sum ; for ( let i = 1 ; i < n - 1 ; i ++ ) { diff = arr [ i + 1 ] - arr [ i ] ; if ( curr_sum > 0 ) curr_sum += diff ; else curr_sum = diff ; if ( curr_sum > max_sum ) max_sum = curr_sum ; } return max_sum ; } let arr = [ 80 , 2 , 6 , 3 , 100 ] ; let n = arr . length ; document . write ( " " + maxDiff ( arr , n ) ) ;