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
< ? php function maxDiff ( $ arr , $ n ) { $ maxDiff = -1 ; $ maxRight = $ arr [ $ n - 1 ] ; for ( $ i = $ n - 2 ; $ i >= 0 ; $ i -- ) { if ( $ arr [ $ i ] > $ maxRight ) $ maxRight = $ arr [ $ i ] ; else { $ diff = $ maxRight - $ arr [ $ i ] ; if ( $ diff > $ maxDiff ) { $ maxDiff = $ diff ; } } } return $ maxDiff ; } $ arr = array ( 1 , 2 , 90 , 10 , 110 ) ; $ n = sizeof ( $ arr ) ; echo " Maximum ▁ difference ▁ is ▁ " , maxDiff ( $ arr , $ n ) ; ? >