Number of local extrema in an array | Java to find number of extrema ; 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 program
import java . io . * ; class GFG { static int extrema ( int a [ ] , int n ) { int count = 0 ; for ( int 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 ; } public static void main ( String args [ ] ) throws IOException { int a [ ] = { 1 , 0 , 2 , 1 } ; int n = a . length ; System . out . println ( extrema ( a , n ) ) ; } }