Number of local extrema in an array | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int extrema ( int a [ ] , int n ) { int count = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { count += ( a [ i ] > a [ i - 1 ] && a [ i ] > a [ i + 1 ] ) ; count += ( a [ i ] < a [ i - 1 ] && a [ i ] < a [ i + 1 ] ) ; } return count ; } int main ( ) { int a [ ] = { 1 , 0 , 2 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << extrema ( a , n ) ; return 0 ; }