//
// main.cpp
// Stock Span
//
// Created by Himanshu on 11/09/21.
//
#include <iostream>
#include <stack>
using namespace std;
void printArray (int arr[], int n) {
for (int i=0; i<n; i++) {
cout<<arr[i]<<" ";
}
cout<<endl;
}
void solve(int S[], int arr[], int n) {
stack<int> st;
S[0] = 1;
st.push(0);
for (int i=1; i<n; i++) {
while (!st.empty() && arr[st.top()] < arr[i]) {
st.pop();
}
if (st.empty()) {
S[i] = i + 1;
} else {
S[i] = i - st.top();
}
st.push(i);
}
}
int main () {
int n = 7;
int arr[] = {100, 80, 60, 70, 60, 75, 85};
int S[n];
cout<<"Initail array:"<<endl;
printArray(arr, n);
solve (S, arr, n);
cout<<"Stock Span:"<<endl;
printArray(S, n);
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBTdG9jayBTcGFuCi8vCi8vICBDcmVhdGVkIGJ5IEhpbWFuc2h1IG9uIDExLzA5LzIxLgovLwoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RhY2s+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgoKCnZvaWQgcHJpbnRBcnJheSAoaW50IGFycltdLCBpbnQgbikgewogICAgZm9yIChpbnQgaT0wOyBpPG47IGkrKykgewogICAgICAgIGNvdXQ8PGFycltpXTw8IiAiOwogICAgfQogICAgY291dDw8ZW5kbDsKfQoKdm9pZCBzb2x2ZShpbnQgU1tdLCBpbnQgYXJyW10sIGludCBuKSB7CiAgICBzdGFjazxpbnQ+IHN0OwogICAgCiAgICBTWzBdID0gMTsKICAgIHN0LnB1c2goMCk7CiAgICAKICAgIGZvciAoaW50IGk9MTsgaTxuOyBpKyspIHsKICAgICAgICAKICAgICAgICB3aGlsZSAoIXN0LmVtcHR5KCkgJiYgYXJyW3N0LnRvcCgpXSA8IGFycltpXSkgewogICAgICAgICAgICBzdC5wb3AoKTsKICAgICAgICB9CiAgICAgICAgCiAgICAgICAgaWYgKHN0LmVtcHR5KCkpIHsKICAgICAgICAgICAgU1tpXSA9IGkgKyAxOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIFNbaV0gPSBpIC0gc3QudG9wKCk7CiAgICAgICAgfQogICAgICAgIAogICAgICAgIHN0LnB1c2goaSk7CiAgICB9Cn0KCmludCBtYWluICgpIHsKICAgIGludCBuID0gNzsKICAgIGludCBhcnJbXSA9IHsxMDAsIDgwLCA2MCwgNzAsIDYwLCA3NSwgODV9OwogICAgaW50IFNbbl07CiAgICAKICAgIGNvdXQ8PCJJbml0YWlsIGFycmF5OiI8PGVuZGw7CiAgICBwcmludEFycmF5KGFyciwgbik7CgogICAgc29sdmUgKFMsIGFyciwgbik7CiAgICAKICAgIGNvdXQ8PCJTdG9jayBTcGFuOiI8PGVuZGw7CiAgICBwcmludEFycmF5KFMsIG4pOwoKICAgIHJldHVybiAwOwp9Cg==