C++ code to count local extrema of given array


Suppose we have an array A with n elements. Some element of this array A[i] is called a local minimum if and only if it is strictly less than both of its neighbors. Also if it is strictly greater than its neighbors it will be local maximum. For A[0] and A[n-1] as there are only one neighbor they are not maxima or minima. We have to find the number of local extrema in the given array.

So, if the input is like A = [1, 5, 2, 5], then the output will be 2, because 5 at A[1] is local maxima and 2 at A[2] is local minima.

Steps

To solve this, we will follow these steps −

sum := 0
n := size of A
for initialize i := 1, when i < n - 1, update (increase i by 1), do:
   if (A[i] < A[i - 1] and A[i] < A[i + 1]) or (A[i] > A[i + 1] and A[i] > A[i - 1]), then:
      (increase sum by 1)
   return sum

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int sum = 0;
   int n = A.size();
   for (int i = 1; i < n - 1; i++)
      if ((A[i] < A[i - 1] && A[i] < A[i + 1]) || (A[i] > A[i + 1] && A[i] > A[i - 1]))
         sum++;
   return sum;
}
int main(){
   vector<int> A = { 1, 5, 2, 5 };
   cout << solve(A) << endl;
}

Input

{ 1, 5, 2, 5 }

Output

2

Updated on: 29-Mar-2022

358 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements