The Sparse Table is a data structure that maintains a sequence of numbers by maintaining
This requires space.
Build
Build builds a Sparse Table for in time and space.
Algorithm
Lemma
Applying the lemma to find yields an algorithm that solves the problem in time and space.
void build(int n, const std::vector<int> &a) {
f.assign(std::__lg(n) + 1, a);
for (int i = 1; i <= std::__lg(n); i++) {
for (int j = 0; j + (1 << i) <= n; j++) {
f[i][j] = std::max(f[i - 1][j], f[i - 1][j + (1 << (i - 1))]);
}
}
}Range Maximum Query
Range Maximum Query computes in time and space.
Algorithm
Lemma
Applying the lemma to find yields an algorithm that solves the problem in time and space.
int range_max_query(int l, int r) {
int i = std::__lg(r - l);
return std::max(f[i][l], f[i][r - (1 << i)]);
}