-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
41 lines (37 loc) · 1.33 KB
/
Copy pathsolution.cpp
File metadata and controls
41 lines (37 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <bits/stdc++.h>
using namespace std;
/*
I compute Catalan numbers up to n using DP, then for each value
count how many elements are smaller (using a sorted copy -> rank).
The answer for element arr[i] is Catalan[left_count] * Catalan[right_count].
*/
class Solution {
public:
vector<int> countBSTs(vector<int>& arr) {
int n = arr.size();
vector<int> ans(n, 0);
if (n == 0) return ans;
// 1) Compute catalan numbers up to n (safe as n is small here).
vector<int> catalan(n+1, 0);
catalan[0] = 1;
for (int i = 1; i <= n; ++i) {
long long sum = 0;
for (int j = 0; j < i; ++j) {
sum += 1LL * catalan[j] * catalan[i-1-j];
}
catalan[i] = (int)sum;
}
// 2) Map value -> number of elements smaller than it (rank)
vector<int> sorted_arr = arr;
sort(sorted_arr.begin(), sorted_arr.end());
unordered_map<int,int> rank;
for (int i = 0; i < n; ++i) rank[sorted_arr[i]] = i;
// 3) For each element compute catalan[left] * catalan[right]
for (int i = 0; i < n; ++i) {
int left = rank[arr[i]];
int right = n - 1 - left;
ans[i] = catalan[left] * catalan[right];
}
return ans;
}
};