// C# program for the above approach
using System;
public class GFG{
static readonly int MAX = 500;
// Stores the index for the minimum
// value in the subarray arr[i, j]
static int [,]lookup = new int[MAX, MAX];
// Structure for query range
class Query {
public int L, R;
public Query(int l, int r) {
L = l;
R = r;
}
};
// Function to fill the lookup array
// lookup[,] in the bottom up manner
static void preprocess(int []arr, int n)
{
// Initialize M for the intervals
// with length 1
for (int i = 0; i < n; i++)
lookup[i,0] = i;
// Find the values from smaller
// to bigger intervals
for (int j = 1; (1 << j) <= n; j++) {
// Compute minimum value for
// all intervals with size 2^j
for (int i = 0; (i + (1 << j) - 1) < n; i++) {
// For arr[2,10], compare
// arr[lookup[0,3]] and
// arr[lookup[3,3]]
if (arr[lookup[i,j - 1]]
< arr[lookup[i + (1 << (j - 1)),j - 1]])
lookup[i,j] = lookup[i,j - 1];
// Otherwise
else
lookup[i,j]
= lookup[i + (1 << (j - 1)),j - 1];
}
}
}
// Function find minimum of absolute
// difference of all adjacent element
// in subarray arr[L..R]
static int query(int []arr, int L, int R)
{
// For [2, 10], j = 3
int j = (int)Math.Log(R - L + 1);
// For [2, 10], compare arr[lookup[0,3]]
// and arr[lookup[3,3]],
if (arr[lookup[L,j]]
<= arr[lookup[R - (1 << j) + 1,j]])
return arr[lookup[L,j]];
else
return arr[lookup[R - (1 << j) + 1,j]];
}
// Function to find the minimum of the
// ranges for M queries
static void Min_difference(int []arr, int n,
Query []q, int m)
{
// Fills table lookup[n,Log n]
preprocess(arr, n);
// Compute sum of all queries
for (int i = 0; i < m; i++) {
// Left and right boundaries
// of current range
int L = q[i].L, R = q[i].R;
// Print sum of current query range
Console.WriteLine(query(arr, L, R - 1));
}
}
// Function to find the minimum absolute
// difference in a range
static void minimumDifference(int []arr, Query []q,
int N, int m)
{
// diff[] is to stores the absolute
// difference of adjacent elements
int []diff = new int[N];
for (int i = 0; i < N - 1; i++)
diff[i] = Math.Abs(arr[i] - arr[i + 1]);
// Call Min_difference to get minimum
// difference of adjacent elements
Min_difference(diff, N - 1, q, m);
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 2, 6, 1, 8, 3, 4 };
int N = arr.Length;
Query []Q = { new Query( 0, 3 ), new Query( 1, 5 ), new Query( 4, 5 ) };
int M = Q.Length;
minimumDifference(arr, Q, N, M);
}
}
// This code is contributed by shikhasingrajput