Count of array elements which is smaller than both its adjacent elements
Last Updated :
20 Feb, 2022
Given an array arr[] of size N, the task is to find the number of valley points in the array.
Valley Point: Any elements of the array is known as a valley point if it is smaller than both its adjacent elements, i.e. .
Examples:
Input: arr[] = {3, 2, 5}
Output: 1
Explanation:
There is only one valley point. That is arr[1].
Input: arr[] = {5, 4, 8, 3, 6}
Output: 2
Explanation:
There are two valley points. That is arr[1] and arr[3].
Approach: The idea is to iterate over the array from 1 to and for each element check for that element is a valley point or not if yes, then increment the count of the valley point by 1.
if (arr[i-1] > arr[i] < arr[i])
count += 1;
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int countValleys( int n, int arr[])
{
int count = 0, temp = 0;
for ( int i = 1; i < n - 1; i++)
{
if (arr[i - 1] > arr[i] &&
arr[i] < arr[i + 1])
{
count++;
}
}
return count;
}
int main()
{
int arr[] = { 3, 2, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << countValleys(n, arr);
}
|
Java
import java.io.*;
class GFG {
static int countValleys( int n, int arr[])
{
int count = 0 , temp = 0 ;
for ( int i = 1 ; i < n - 1 ; i++) {
if (arr[i - 1 ] > arr[i]
&& arr[i] < arr[i + 1 ]) {
count++;
}
}
return count;
}
public static void main(String[] args)
{
int arr[] = { 3 , 2 , 5 };
int n = arr.length;
System.out.println(
countValleys(n, arr));
}
}
|
Python3
def countValleys(n, arr):
count = 0 ; temp = 0 ;
for i in range ( 1 , n):
if (arr[i - 1 ] > arr[i] and
arr[i] < arr[i + 1 ]):
count + = 1 ;
return count;
arr = [ 3 , 2 , 5 ];
n = len (arr);
print (countValleys(n, arr));
|
C#
using System;
class GFG{
static int countValleys( int n, int []arr)
{
int count = 0;
for ( int i = 1; i < n - 1; i++)
{
if (arr[i - 1] > arr[i] &&
arr[i] < arr[i + 1])
{
count++;
}
}
return count;
}
public static void Main()
{
int []arr = { 3, 2, 5 };
int n = arr.Length;
Console.Write(countValleys(n, arr));
}
}
|
Javascript
<script>
function countValleys(n, arr)
{
let count = 0, temp = 0;
for (let i = 1; i < n - 1; i++)
{
if (arr[i - 1] > arr[i] &&
arr[i] < arr[i + 1])
{
count++;
}
}
return count;
}
let arr = [ 3, 2, 5 ];
let n = arr.length;
document.write(countValleys(n, arr));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...