// C# program for the above approach
using System;
public class GFG
{
// Function to find the maximum and
// minimum array elements up to the i-th index
static void prefixArr(int[] arr, int[,] prefix, int N)
{
// Traverse the array
for (int i = 0; i < N; i++)
{
if (i == 0)
{
prefix[i, 0] = arr[i];
prefix[i, 1] = arr[i];
}
else
{
// Compare current value with maximum
// and minimum values up to previous index
prefix[i, 0] = Math.Max(prefix[i - 1, 0], arr[i]);
prefix[i, 1] = Math.Min(prefix[i - 1, 1], arr[i]);
}
}
}
// Function to find the maximum and
// minimum array elements from i-th index
static void suffixArr(int[] arr, int[,] suffix, int N)
{
// Traverse the array in reverse
for (int i = N - 1; i >= 0; i--)
{
if (i == N - 1)
{
suffix[i, 0] = arr[i];
suffix[i, 1] = arr[i];
}
else
{
// Compare current value with maximum
// and minimum values in the next index
suffix[i, 0] = Math.Max(suffix[i + 1, 0], arr[i]);
suffix[i, 1] = Math.Min(suffix[i + 1, 1], arr[i]);
}
}
}
// Function to find the maximum and
// minimum array elements for each query
static void maxAndmin(int[,] prefix,
int[,] suffix,
int N, int L, int R)
{
int maximum, minimum;
// If no index remains after
// excluding the elements
// in a given range
if (L == 0 && R == N - 1)
{
Console.WriteLine("No maximum and minimum value");
return;
}
// Find maximum and minimum from
// from the range [R + 1, N - 1]
else if (L == 0)
{
maximum = suffix[R + 1, 0];
minimum = suffix[R + 1, 1];
}
// Find maximum and minimum from
// from the range [0, N - 1]
else if (R == N - 1)
{
maximum = prefix[L - 1, 0];
minimum = prefix[R - 1, 1];
}
// Find maximum and minimum values from the
// ranges [0, L - 1] and [R + 1, N - 1]
else
{
maximum = Math.Max(prefix[L - 1, 0],
suffix[R + 1, 0]);
minimum = Math.Min(prefix[L - 1, 1],
suffix[R + 1, 1]);
}
// Print the maximum and minimum value
Console.WriteLine(maximum + " " + minimum);
}
// Function to perform queries to find the
// minimum and maximum array elements excluding
// elements from a given range
static void MinMaxQueries(int[] a, int[,] Q)
{
// Size of the array
int N = a.GetLength(0);
// Size of query array
int q = Q.GetLength(0);
// prefix[i][0]: Stores the maximum
// prefix[i][1]: Stores the minimum value
int[,] prefix = new int[N, 2];
// suffix[i][0]: Stores the maximum
// suffix[i][1]: Stores the minimum value
int[,] suffix = new int[N, 2];
// Function calls to store
// maximum and minimum values
// for respective ranges
prefixArr(a, prefix, N);
suffixArr(a, suffix, N);
for (int i = 0; i < q; i++)
{
int L = Q[i, 0];
int R = Q[i, 1];
maxAndmin(prefix, suffix, N, L, R);
}
}
// Driver Code
static public void Main ()
{
// Given array
int[] arr = { 2, 3, 1, 8, 3, 5, 7, 4 };
int[,] queries = { { 4, 6 }, { 0, 4 },
{ 3, 7 }, { 2, 5 } };
MinMaxQueries(arr, queries);
}
}
// This code is contributed by sanjoy_62.