Editorial for Maximum-Minimum Difference


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

Authors: Eric_Zhang

The best way to solve this problem is by using a Sparse table. For every subarray of length 2^i (where i 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 A = [1,3,3,4,5,2,8], if we want to find the minimum in the range of 2-7, we can split this subarray of length 6 into two subarrays of length 4 with overlap. We split 2-7 into 2-5 and 4-7. This way, we can find the minimum in a single operation, namely by finding the minimum of the ranges 2-5 and 4-7 (this is because 4 = 2^2 so the minimum of all subarrays of length 4 are recorded in the sparse table.)

A sparse table is stored in a 2D array with K rows and N columns. N is the amount of elements in the array and K is a number such that K \geq \text{log}_2 N. K=25 is sufficient for N \leq 10^7.

int sparse[25][N]

The first row contains the original array

for (int i = 0; i < N; i++):
  sparse[0][i] = input

The i'th row contains the minimum value of subarrays of length 2^i, which can be found by taking the minimum of two subarrays with length 2^{i-1}. \mathbf{sparse}[i][j] contains the minimum of the subarray of length 2^i starting at index j.

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 2^i, we iterate until 2^i \leq N. The second line, we iterate over all indices except for the last 2^i-1. For each subarray of length 2^i starting at j, we find the minimum of two subarrays of length 2^{i-1} starting at j and j+2^{i-1}. Thus, we've create our sparse table.

Given a range (l,r), we first find the largest power of two that can fit inside the range, let that be 2^e. Next, we find minimum of \mathbf{sparse}[e][l] and \mathbf{sparse}[e][r-(1<<e)+1] 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 e so to get \text{log}_2(b-a+1), we must do \text{log}(b-a+1)/ \text{log}(2)


Comments

There are no comments at the moment.