Link to this code:
https://cses.fi/paste/623b40d56d2694b111b4d92/// Sebastian Galindo
#include <bits/stdc++.h>
using namespace std;
constexpr char nl = '\n';
constexpr int N = 2e5 + 5;
struct Node {
pair<int, int> val;
Node *l = nullptr, *r = nullptr;
};
int n;
int dp(Node *root, Node *p) {
if (root == nullptr)
return 0;
return max(dp(root->l, root), dp(root->r, root)) +
(p == nullptr or p->val.first != root->val.first);
}
void solve() {
cin >> n;
stack<Node *> st;
for (int i = 0; i < n; i++) {
int v;
cin >> v;
Node *nw = new Node();
nw->val = {v, i};
Node *last = nullptr;
while (not st.empty() and st.top()->val < nw->val) {
last = st.top();
st.pop();
}
nw->l = last;
if (not st.empty())
st.top()->r = nw;
st.push(nw);
}
Node *root = nullptr;
while (not st.empty())
root = st.top(), st.pop();
cout << dp(root, nullptr) << nl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T = 1;
while (T--) {
solve();
}
return 0;
}