Initialize max element from right side
$ 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 ; }