Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.
More formally,
G[i] for an element A[i] is an element A[j] such that
j is maximum possible AND
j < i AND
A[j] < A[i]
Elements for which no smaller element exist, consider the next smaller element as -1.
Example:
Input: n = 8, a = [39, 27, 11 ,4 ,24, 32 ,32, 1]
Output: -1 -1 -1 -1 4 24 24 -1
Approach
C++
#include <bits/stdc++.h>using namespace std;void nearestSmallestElements(int n, int a[]){stack<int> st;int arr[n];for (int i = 0; i < n; i++){while (!st.empty() && st.top() >= a[i])st.pop();if (st.empty())arr[i] = -1;elsearr[i] = st.top();st.push(a[i]);}for (int i = 0; i < n; i++)cout << arr[i] << " ";}int main(){int n = 8;int a[n] = {39, 27, 11, 4, 24, 32, 32, 1};nearestSmallestElements(n, a);return 0;}
No comments:
Post a Comment