JavaScript Program for Number of Local Extrema in an Array



JavaScript Program for the Number of local extrema in an array is a common problem in the field of computer science and data analysis. Local extrema are the peaks and valleys in a sequence of numbers.

In this article we are having two arrays, our task is to write a Javascript program for number of local extrema in an array.

Local extrema in array

Example

Input:
arr1 = [1, 2, 3, 2, 1, 4, 5, 6, 5, 4, 3, 2, 1];
First local extrema: 3, {2  2}
Second local extrema: 1, {2 > 1  5}

Output:
3

Input:
arr2 = [2, 4, 6, 8, 10];

Output:
0

Steps to Count Number of Local Extrema in Array

We will be following below mentioned steps for number of local extrema in an array. We will check for an element to be either greater than its both neighbour elements or to be smaller than both its neighbour elements. Both, the start and end element is not considered as local extrema as they have just one neighbour.

  • We have declared two arrays, arr1 and arr2 and defined a function localExtrema() and passed an array arr as argument.
  • Initialize a variable count to 0 to keep track of the number of local extrema.
  • We have used for loop to iterate over elements of the array.
  • For each element in the array, check if it is greater than its previous and next elements or lesser than its previous and next elements. If yes, then increment the count variable.
  • After completing the loop, return the count variable as the number of local extrema in the array. The count is displayed in web console using console.log() method.

Example

Here is a complete example code implementing above mentioned steps for Number of local extrema in an array using for loop and if/else statement.

const arr1 = [1, 2, 3, 2, 1, 4, 5, 6, 5, 4, 3, 2, 1];
const arr2 = [2, 4, 6, 8, 10];
function localExtrema(arr) {
    let count = 0;
    for (let i = 1; i  arr[i - 1] && arr[i] > arr[i + 1]) || 
            (arr[i] 

Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.
Updated on: 2024-12-06T17:17:21+05:30

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements