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
< ? php function maxDiff ( $ arr , $ n ) { $ diff = $ arr [ 1 ] - $ arr [ 0 ] ; $ curr_sum = $ diff ; $ max_sum = $ curr_sum ; for ( $ 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 ; } $ arr = array ( 80 , 2 , 6 , 3 , 100 ) ; $ n = sizeof ( $ arr ) ; echo " Maximum ▁ difference ▁ is ▁ " , maxDiff ( $ arr , $ n ) ; ? >