Number of local extrema in an array
Last Updated :
29 Jul, 2022
You are given an array on n-elements. An extrema is an elements which is either greater than its both of neighbors or less than its both neighbors. You have to calculate the number of local extrema in given array.
Note : 1st and last elements are not extrema.
Examples :
Input : a[] = {1, 5, 2, 5}
Output : 2
Input : a[] = {1, 2, 3}
Output : 0
Approach :For calculating number of extrema we have to check whether an element is maxima or minima i.e. whether it is greater than both of its neighbors or less than both neighbors. For this simply iterate over the array and for each elements check its possibility of being an extrema.
Note: a[0] and a[n-1] has exactly one neighbour each, they are neither minima nor maxima.
Implementation:
C++
#include <bits/stdc++.h>
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;
}
|
Java
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));
}
}
|
Python3
def extrema(a, n):
count = 0
for i in range ( 1 , n - 1 ) :
count + = (a[i] > a[i - 1 ] and a[i] > a[i + 1 ]);
count + = (a[i] < a[i - 1 ] and a[i] < a[i + 1 ]);
return count
a = [ 1 , 0 , 2 , 1 ]
n = len (a)
print (extrema(a, n))
|
C#
using System;
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()
{
int []a = { 1, 0, 2, 1 };
int n = a.Length;
Console.WriteLine(extrema(a, n));
}
}
|
PHP
<?php
function extrema( $a , $n )
{
$count = 0;
for ( $i = 1; $i < $n - 1; $i ++)
{
$count += ( $a [ $i ] > $a [ $i - 1] and
$a [ $i ] > $a [ $i + 1]);
$count += ( $a [ $i ] < $a [ $i - 1] and
$a [ $i ] < $a [ $i + 1]);
}
return $count ;
}
$a = array ( 1, 0, 2, 1 );
$n = count ( $a );
echo extrema( $a , $n );
?>
|
Javascript
<script>
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));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...