Editorial for Maximum-Minimum Difference
Submitting an official solution before solving the problem yourself is a bannable offence.
Authors:
The best way to solve this problem is by using a Sparse table. For every subarray of length (where is a natural), the sparse table records the minimum value of that subarray. This way, if we want to find the minimum value within any range, we can simply find the minimum of two subarrays. As an example, consider the following:
Given an array , if we want to find the minimum in the range of , we can split this subarray of length into two subarrays of length with overlap. We split into and . This way, we can find the minimum in a single operation, namely by finding the minimum of the ranges and (this is because so the minimum of all subarrays of length are recorded in the sparse table.)
A sparse table is stored in a 2D array with rows and columns. is the amount of elements in the array and is a number such that . is sufficient for .
int sparse[25][N]
The first row contains the original array
for (int i = 0; i < N; i++):
sparse[0][i] = input
The 'th row contains the minimum value of subarrays of length , which can be found by taking the minimum of two subarrays with length . contains the minimum of the subarray of length starting at index .
for(int i = 1; (1<<i)<=N; i++){
for(int j = 0; j + (1<<i) <= N; j++){
sparse[i][j] = min(sparse[i-1][j],sparse[i-1][j+(1<<(i-1))])
}
}
In the first line, we iterate over the columns. Because each column contains the minimum of a subarray of length , we iterate until . The second line, we iterate over all indices except for the last . For each subarray of length starting at , we find the minimum of two subarrays of length starting at and . Thus, we've create our sparse table.
Given a range , we first find the largest power of two that can fit inside the range, let that be . Next, we find minimum of and to get our answer
int l = input - 1
int r = input - 1
int e = int (log(b-a+1)/log(2))
print(min(sparse[e][l],sparse[e][r-(1<<e)+1]))
Footnote For Java, the log function takes base so to get , we must do
Comments