In this problem, we are given an array. Our task is to return the greatest element that precedes the current element in the array otherwise print -1.
Let’s take an example to understand the problem
Input: {6, 2, 7, 1, 5, 3}
Output: -1, 6, -1, 7, 7, 7To solve this problem, an easy and obvious solution will be using nested loops that will check greater element in the preceding part of the array.
Program to show the implementation of our solution
Example
#include <iostream>
using namespace std;
void preceddingGreatestElement(int arr[], int n){
cout << "-1\t";
int i, j;
for (i = 1; i < n; i++) {
for (j = i-1; j >= 0; j--) {
if (arr[i]<arr[j]) {
cout<<arr[j]<< "\t";
break;
}
}
if (j == -1)
cout << "-1\t";
}
}
int main() {
int arr[] = { 6, 2, 7, 1, 12, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
preceddingGreatestElement(arr, n);
return 0;
}Output
-1 6 -1 7 -1 12
A more effective solution to solve our problem is by using the stack data structure. And maintaining the preceding larger number at the top of the stack.
Program to show the implementation of this solution
Example
#include <bits/stdc++.h>
using namespace std;
void preceddingGreatestElement(int arr[], int n) {
stack<int> elements;
elements.push(arr[0]);
cout << "-1\t";
for (int i = 1; i < n; i++) {
while (elements.empty() == false && elements.top() < arr[i])
elements.pop();
if(elements.empty())
cout<<"-1\t";
else
cout<<elements.top()<<"\t";
elements.push(arr[i]);
}
}
int main() {
int arr[] = { 6, 2, 7, 1, 12, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
preceddingGreatestElement(arr, n);
return 0;
}Output
-1 6 -1 7 -1 12