Given an array of N integers. The task is to print the elements from the array which are greater than their immediate previous and next elements.
Examples :
Input : arr[] = {2, 3, 1, 5, 4, 9, 8, 7, 5}
Output : 3, 5, 9
In above given example 3 is greater than its
left element 2 and right element 1.
Similar logic is applied to other elements
hence our final output is 3, 5, 9.
Input : arr[] = {1, 2, 3, 2, 1}
Output : 3
Approach: Since there is no element on the left of the first element(arr[0]) and there is no element to the right of last element(arr[N-1]) so these two elements will be excluded from the final answer.
Now, traverse the array starting from the index 1 to N-2 and for every element arr[i] check if arr[i] > arr[i-1] and arr[i] > arr[i+1].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printElements( int arr[], int n)
{
for ( int i = 1; i < n - 1; i++) {
if (arr[i] > arr[i - 1] and arr[i] > arr[i + 1])
cout << arr[i] << " " ;
}
}
int main()
{
int arr[] = { 2, 3, 1, 5, 4, 9, 8, 7, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
printElements(arr, n);
return 0;
}
|
Java
class GfG
{
static void printElements( int arr[], int n)
{
for ( int i = 1 ; i < n - 1 ; i++)
{
if (arr[i] > arr[i - 1 ] && arr[i] > arr[i + 1 ])
System.out.print(arr[i] + " " );
}
}
public static void main(String[] args)
{
int arr[] = { 2 , 3 , 1 , 5 , 4 , 9 , 8 , 7 , 5 };
int n = arr.length;
printElements(arr, n);
}
}
|
Python3
def printElements(arr, n):
for i in range ( 1 , n - 1 , 1 ):
if (arr[i] > arr[i - 1 ] and
arr[i] > arr[i + 1 ]):
print (arr[i], end = " " )
if __name__ = = '__main__' :
arr = [ 2 , 3 , 1 , 5 , 4 , 9 , 8 , 7 , 5 ]
n = len (arr)
printElements(arr, n)
|
C#
using System;
public class GfG
{
public static void printElements( int [] arr, int n)
{
for ( int i = 1; i < n - 1; i++)
{
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1])
{
Console.Write(arr[i] + " " );
}
}
}
public static void Main( string [] args)
{
int [] arr = new int [] {2, 3, 1, 5, 4, 9, 8, 7, 5};
int n = arr.Length;
printElements(arr, n);
}
}
|
PHP
<?php
function printElements( $arr , $n )
{
for ( $i = 1; $i < $n - 1; $i ++)
{
if ( $arr [ $i ] > $arr [ $i - 1] and
$arr [ $i ] > $arr [ $i + 1])
echo $arr [ $i ] . " " ;
}
}
$arr = array (2, 3, 1, 5, 4, 9, 8, 7, 5);
$n = sizeof( $arr );
printElements( $arr , $n );
|
Javascript
<script>
function printElements(arr, n)
{
for ( var i = 1; i < n - 1; i++) {
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1])
document.write( arr[i] + " " );
}
}
var arr = [ 2, 3, 1, 5, 4, 9, 8, 7, 5 ];
var n = arr.length;
printElements(arr, n);
</script>
|
Time Complexity : O(n)
Auxiliary Space : O(1)