 Open in App
Not now

# Php Program for Number of local extrema in an array

• Last Updated : 17 Jan, 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 and a[n-1] has exactly one neighbour each, they are neither minima nor maxima.

## PHP

 ` ``\$a``[``\$i` `- 1] ``and`  `                   ``\$a``[``\$i``] > ``\$a``[``\$i` `+ 1]); ` ` `  `        ``// check if a[i] is  ` `        ``// less than both its  ` `        ``// neighbours, then  ` `        ``// add 1 to x ` `        ``\$count` `+= (``\$a``[``\$i``] < ``\$a``[``\$i` `- 1] ``and`  `                   ``\$a``[``\$i``] < ``\$a``[``\$i` `+ 1]); ` `    ``} ` ` `  `    ``return` `\$count``; ` `} ` ` `  `// Driver Code ` `\$a` `= ``array``( 1, 0, 2, 1 ); ` `\$n` `= ``count``(``\$a``); ` `echo` `extrema(``\$a``, ``\$n``); ` ` `  `// This code is contributed by anuj_67. ` `?> `

Output :

`2`

Please refer complete article on Number of local extrema in an array for more details!

My Personal Notes arrow_drop_up
Related Articles