// C# code for the above approach
using System;
using System.Collections;
class GFG {
// Function to compute
// next greater element indices on the
// right side on any index
static int[] rightGreaterElement(int[] arr, int n)
{
// to store the elements of array arr
// with their index
int[,] B = new int[n,2];
for (int i = 0; i < n; i++) {
B[i,0] = arr[i];
B[i,1] = i;
}
// to store indices of next greater element
// on the right side
int[] vec = new int[n];
Array.Fill(vec, -1);
// to store the pairs
Stack st = new Stack();
for (int i = 0; i < n; i++) {
// if the stack is empty,
// push the pair
if (st.Count == 0) {
st.Push(new Tuple<int,int>(B[i,0], B[i,1]));
}
else {
// Pop and assign till
// the top is smaller
while (st.Count > 0
&& ((Tuple<int,int>)st.Peek()).Item1 < B[i,0]) {
vec[((Tuple<int,int>)st.Peek()).Item2] = B[i,1];
st.Pop();
}
st.Push(new Tuple<int,int>(B[i,0], B[i,1]));
}
}
// assign n to element
// having no next greater element
while (st.Count > 0) {
vec[((Tuple<int,int>)st.Peek()).Item2] = n;
st.Pop();
}
// return the vector
return vec;
}
// Function to compute next greater element
// indices on the left side on any index
static int[] leftGreaterElement(int[] arr, int n)
{
// store the elements of array arr
// with their index
int[,] B = new int[n,2];
for (int i = 0; i < n; i++) {
B[i,0] = arr[i];
B[i,1] = i;
}
// array to store indices of next
// greater element on the left side
int[] vec = new int[n];
Array.Fill(vec, -1);
// stack to store the pairs
Stack st = new Stack();
for (int i = n - 1; i >= 0; i--) {
// if the stack is empty, push the pair
if (st.Count == 0) {
st.Push(new Tuple<int,int>(B[i,0], B[i,1]));
}
else {
// pop and assign till top is smaller
while (st.Count > 0
&& ((Tuple<int,int>)st.Peek()).Item1 < B[i,0]) {
vec[((Tuple<int,int>)st.Peek()).Item2] = B[i,1];
st.Pop();
}
st.Push(new Tuple<int,int>(B[i,0], B[i,1]));
}
}
// assign -1 to element having
// no next greater element
while (st.Count > 0) {
vec[((Tuple<int,int>)st.Peek()).Item2] = -1;
st.Pop();
}
// returning the vector
// with indices of next greater
// elements on the left side.
return vec;
}
// Function to print the maximum
// length of subarrays for all
// indices where A[i] is the
// maximum element in the subarray
static void maximumSubarrayLength(int[] arr, int N)
{
// array having index of next
// greater element on the right side.
int[] right = rightGreaterElement(arr, N);
// array having index of next
// greater element on the left side.
int[] left = leftGreaterElement(arr, N);
// print the range between the
// next greater elements on both the sides.
for (int i = 0; i < N; i++) {
int l = left[i];
int r = right[i];
Console.Write((r - l - 1) + " ");
}
}
static void Main()
{
// Input
int[] arr = { 62, 97, 49, 59, 54, 92, 21 };
int N = arr.Length;
// Function call
maximumSubarrayLength(arr, N);
}
}
// This code is contributed by divyesh072019.