Number of local extrema in an array | function to find local extremum ; start loop from position 1 till n - 1 ; check if a [ i ] is greater than both its neighbours then add 1 to x ; check if a [ i ] is less than both its neighbours , then add 1 to x ; Driver Code
< ? php function extrema ( $ a , $ n ) { $ count = 0 ; for ( $ i = 1 ; $ i < $ n - 1 ; $ i ++ ) { $ count += ( $ a [ $ i ] > $ a [ $ i - 1 ] and $ a [ $ i ] > $ a [ $ i + 1 ] ) ; $ count += ( $ a [ $ i ] < $ a [ $ i - 1 ] and $ a [ $ i ] < $ a [ $ i + 1 ] ) ; } return $ count ; } $ a = array ( 1 , 0 , 2 , 1 ) ; $ n = count ( $ a ) ; echo extrema ( $ a , $ n ) ; ? >