

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Elements greater than the previous and next element in an Array in C++
In this problem, we are given an array arr[] of n positive integers. Our task is to create a program to find the elements greater than the previous and next element in an Array.
Code Description: We need to find the elements of the array that satisfy the condition, the element is greater that the element at index 1 less than it and also is greater than the element at index 1 greater than it.
Let’s take an example to understand the problem,
Input: arr[] = {3, 2, 5, 7, 3, 4, 5}
Output: 7
Explanation −
Element with index one less than the current element, 5.
Element with index one more than the current element, 3.
The current element is greater than both.
Solution Approach −
A simple solution to the problem is by checking the condition for each element of the array and then print the element that satisfies the condition.
For this we need to follow these steps−
Step 1: Loop through the elements of the array from index 1 to n-2.
Step 1.1: for each element, arr[i]. We will check if arr[i] > arr[i-1] and arr[i] > arr[i+1].
Step 1.2: If it is true, print arr[i].
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; void findElemenetsInArray(int arr[], int n) { for (int i = 1; i < n-1; i++) if ( (arr[i] > arr[i+1] && arr[i] > arr[i-1]) ) { cout<<arr[i]<<"\t"; } } int main() { int n = 8; int arr[n] = { 5, 4, 7, 1, 17, 8, 3 }; cout<<"The elements that satisfy the given condition are "; findElemenetsInArray(arr, n); return 0; }
Output −
The elements that satisfy the given condition are 7 17
- Related Questions & Answers
- Previous greater element in C++
- Python – Sort Matrix by Number of elements greater than its previous element
- Rearrange an array such that every odd indexed element is greater than its previous in C++
- Next Greater Element in Circular Array in JavaScript
- Next Greater Element in C++
- Find next Smaller of next Greater in an array in C++
- Next Greater Element II in C++
- Next Greater Element III in C++
- Finding element greater than its adjacent elements in JavaScript
- Return the truth value of an array greater than another element-wise in Numpy
- Adding elements of an array until every element becomes greater than or equal to k in C++.
- Finding distance to next greater element in JavaScript
- Mask array elements greater than a given value in Numpy
- Interesting Python Implementation for Next Greater Elements
- Find the Next perfect square greater than a given number in C++