using
System;
using
System.Collections.Generic;
class
GFG{
public
static
int
findMaximumSum(
int
[] a,
int
n)
{
int
[]prev_smaller = findPrevious(a, n);
int
[]next_smaller = findNext(a, n);
int
max_value = 0;
for
(
int
i = 0; i < n; i++)
{
max_value = Math.Max(max_value,
a[i] * (next_smaller[i] -
prev_smaller[i] - 1));
}
return
max_value;
}
public
static
int
[] findPrevious(
int
[] a,
int
n)
{
int
[]ps =
new
int
[n];
ps[0] = -1;
Stack<
int
> stack =
new
Stack<
int
>();
stack.Push(0);
for
(
int
i = 1; i < a.Length; i++)
{
while
(stack.Count > 0 &&
a[stack.Peek()] >= a[i])
stack.Pop();
ps[i] = stack.Count > 0 ? stack.Peek() : -1;
stack.Push(i);
}
return
ps;
}
public
static
int
[] findNext(
int
[] a,
int
n)
{
int
[]ns =
new
int
[n];
ns[n - 1] = n;
Stack<
int
> stack =
new
Stack<
int
>();
stack.Push(n - 1);
for
(
int
i = n - 2; i >= 0; i--)
{
while
(stack.Count > 0 &&
a[stack.Peek()] >= a[i])
stack.Pop();
ns[i] = stack.Count > 0 ? stack.Peek()
: a.Length;
stack.Push(i);
}
return
ns;
}
public
static
void
Main(String []args)
{
int
n = 3;
int
[]a = { 80, 48, 82 };
Console.WriteLine(findMaximumSum(a, n));
}
}