Find indices of all local maxima and local minima in an Array | C ++ program for the above approach ; Function to find all the local maxima and minima in the given array arr [ ] ; Empty vector to store points of local maxima and minima ; Checking whether the first point is local maxima or minima or none ; Iterating over all points to check local maxima and local minima ; Condition for local minima ; Condition for local maxima ; Checking whether the last point is local maxima or minima or none ; Print all the local maxima and local minima indexes stored ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findLocalMaximaMinima ( int n , int arr [ ] ) { vector < int > mx , mn ; if ( arr [ 0 ] > arr [ 1 ] ) mx . push_back ( 0 ) ; else if ( arr [ 0 ] < arr [ 1 ] ) mn . push_back ( 0 ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( ( arr [ i - 1 ] > arr [ i ] ) and ( arr [ i ] < arr [ i + 1 ] ) ) mn . push_back ( i ) ; else if ( ( arr [ i - 1 ] < arr [ i ] ) and ( arr [ i ] > arr [ i + 1 ] ) ) mx . push_back ( i ) ; } if ( arr [ n - 1 ] > arr [ n - 2 ] ) mx . push_back ( n - 1 ) ; else if ( arr [ n - 1 ] < arr [ n - 2 ] ) mn . push_back ( n - 1 ) ; if ( mx . size ( ) > 0 ) { cout << " Points ▁ of ▁ Local ▁ maxima ▁ are ▁ : ▁ " ; for ( int a : mx ) cout << a << " ▁ " ; cout << endl ; } else cout << " There ▁ are ▁ no ▁ points ▁ of ▁ " << " Local ▁ Maxima ▁ STRNEWLINE " ; if ( mn . size ( ) > 0 ) { cout << " Points ▁ of ▁ Local ▁ minima ▁ are ▁ : ▁ " ; for ( int a : mn ) cout << a << " ▁ " ; cout << endl ; } else cout << " There ▁ are ▁ no ▁ points ▁ of ▁ " << " Local ▁ Minima ▁ STRNEWLINE " ; } int main ( ) { int N = 9 ; int arr [ ] = { 10 , 20 , 15 , 14 , 13 , 25 , 5 , 4 , 3 } ; findLocalMaximaMinima ( N , arr ) ; return 0 ; }