# Find closest greater value for every element in array in C++

C++Server Side ProgrammingProgramming

Here we will see how to find the closest greater value for every element in an array. If an element x has next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1.

To solve this, we will use the set in C++ STL. The set is implemented using the binary tree approach. In binary tree always the inorder successor is the next larger element. So we can get the element in O(log n) time.

## Example

#include<iostream>
#include<set>
using namespace std;
void nearestGreatest(int arr[], int n) {
set<int> tempSet;
for (int i = 0; i < n; i++)
tempSet.insert(arr[i]);
for (int i = 0; i < n; i++) {
auto next_greater = tempSet.upper_bound(arr[i]);
if (next_greater == tempSet.end())
cout << -1 << " ";
else
cout << *next_greater << " ";
}
}
int main() {
int arr[] = {10, 5, 11, 10, 20, 12};
int n = sizeof(arr) / sizeof(arr[0]);
nearestGreatest(arr, n);
}

## Output

11 10 12 11 -1 20
Published on 01-Nov-2019 11:28:39