CSES Solutions
#1645Sorting and Searching

Nearest Smaller Value

View on CSES

Solution

1645-Nearest_Smaller_Value.cpp
1#include<bits/stdc++.h>
2using namespace std;
3#define int long long
4signed main(){
5  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
6  int n; cin>>n;
7  int a[n+1]; a[0]=0;
8  stack<int> st; st.emplace(0);
9  for(int i=1;i<=n;++i){
10    cin>>a[i];
11    while(a[st.top()]>=a[i]) st.pop();
12    cout<<st.top()<<" ";
13    st.emplace(i);
14  }
15  cout<<'\n';
16  return 0;
17}

Editorial not yet generated for this problem. Run the editorial generation script to add hints and detailed explanations.