Count of elements which are second smallest among three consecutive elements
Last Updated :
07 Mar, 2022
Given a permutation P of first N natural numbers. The task is to find the number of elements Pi such that Pi is second smallest among Pi – 1, Pi and Pi + 1.
Examples:
Input: P[] = {2, 5, 1, 3, 4}
Output: 1
3 is the only such element.
Input: P[] = {1, 2, 3, 4}
Output: 2
Approach: Traverse the permutation from 1 to N – 2 ( zero-based indexing) and check the below two conditions. If anyone of these conditions satisfy then increment the required answer.
- If P[i – 1] < P[i] < P[i + 1].
- If P[i – 1] > P[i] > P[i + 1].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countElements( int p[], int n)
{
int ans = 0;
for ( int i = 1; i < n - 1; i++) {
if (p[i - 1] > p[i] and p[i] > p[i + 1])
ans++;
else if (p[i - 1] < p[i] and p[i] < p[i + 1])
ans++;
}
return ans;
}
int main()
{
int p[] = { 2, 5, 1, 3, 4 };
int n = sizeof (p) / sizeof (p[0]);
cout << countElements(p, n);
return 0;
}
|
Java
class GFG
{
static int countElements( int p[], int n)
{
int ans = 0 ;
for ( int i = 1 ; i < n - 1 ; i++)
{
if (p[i - 1 ] > p[i] && p[i] > p[i + 1 ])
ans++;
else if (p[i - 1 ] < p[i] && p[i] < p[i + 1 ])
ans++;
}
return ans;
}
public static void main(String []args)
{
int p[] = { 2 , 5 , 1 , 3 , 4 };
int n = p.length;
System.out.println(countElements(p, n));
}
}
|
Python3
def countElements(p, n) :
ans = 0 ;
for i in range ( 1 , n - 1 ) :
if (p[i - 1 ] > p[i] and p[i] > p[i + 1 ]) :
ans + = 1 ;
elif (p[i - 1 ] < p[i] and p[i] < p[i + 1 ]) :
ans + = 1 ;
return ans;
if __name__ = = "__main__" :
p = [ 2 , 5 , 1 , 3 , 4 ];
n = len (p);
print (countElements(p, n));
|
C#
using System;
class GFG
{
static int countElements( int []p, int n)
{
int ans = 0;
for ( int i = 1; i < n - 1; i++)
{
if (p[i - 1] > p[i] && p[i] > p[i + 1])
ans++;
else if (p[i - 1] < p[i] && p[i] < p[i + 1])
ans++;
}
return ans;
}
public static void Main(String []args)
{
int []p = { 2, 5, 1, 3, 4 };
int n = p.Length;
Console.WriteLine(countElements(p, n));
}
}
|
Javascript
<script>
function countElements(p , n)
{
var ans = 0;
for (i = 1; i < n - 1; i++) {
if (p[i - 1] > p[i] && p[i] > p[i + 1])
ans++;
else if (p[i - 1] < p[i] && p[i] < p[i + 1])
ans++;
}
return ans;
}
var p = [ 2, 5, 1, 3, 4 ];
var n = p.length;
document.write(countElements(p, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...