The Sparse Table is a data structure that maintains an array of numbers by maintaining

which costs a space of .

Build

Build builds a Sparse Table for in time and space.

Algorithm

Lemma

Applying the lemma yields to find 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)]);
}