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
function extrema ( a , n ) { let count = 0 ; for ( let i = 1 ; i < n - 1 ; i ++ ) { if ( a [ i ] > a [ i - 1 ] && a [ i ] > a [ i + 1 ] ) count += 1 ; if ( a [ i ] < a [ i - 1 ] && a [ i ] < a [ i + 1 ] ) count += 1 ; } return count ; } let a = [ 1 , 0 , 2 , 1 ] ; let n = a . length ; document . write ( extrema ( a , n ) ) ;