Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Largest Rectangle in a Histogram

A histogram is made of a number of contiguous bars, which have same width.

For a given histogram with $N$ bars which have a width of 1 and a height of $h_i$ = $h_1, h_2, ... , h_N$ respectively, find the area of the largest rectangular area.

Constraints

$1 \leq N \leq 10^5$

$0 \leq h_i \leq 10^9$

Input

The input is given in the following format.

$N$

$h_1$ $h_2$ ... $h_N$

Output

Print the area of the largest rectangle.

Sample Input 1

8
2 1 3 5 3 4 2 1

Sample Output 1

12

Sample Input 2

3
2 0 1

Sample Output 2

2

Solution in C# (judge verdict: Accepted)

using System.Linq;
using static System.Math;
using System.Collections.Generic;
using System;

public class P
{
    public int p { get; set; }
    public int h { get; set; }
}

public class hello
{
    public static void Main()
    {
        var n = int.Parse(Console.ReadLine().Trim()) + 1;
        var s = Console.ReadLine().Trim() + " 0";
        string[] line = s.Split(' ');
        var a = Array.ConvertAll(line, int.Parse);
        var ans = getAns(a, n);
        Console.WriteLine(ans);
    }
    static long getAns(int[] a, int n)
    {
        var ans = 0L; var lastp = 0;
        var st = new Stack<P>();
        for (int i = 0; i < n; i++)
        {
            if (st.Count() == 0) st.Push(new P { p = i, h = a[i] });
            else
            {
                var w = st.Peek();
                if (a[i] > w.h) st.Push(new P { p = i, h = a[i] });
                else if (a[i] < w.h)
                {
                    while (true)
                    {
                        ans = Max(ans, (long)(i - w.p) * w.h);
                        lastp = w.p;
                        st.Pop();
                        if (st.Count() == 0) break;
                        w = st.Peek();
                        if (a[i] <= w.h) continue;
                        else break;
                    }
                    st.Push(new P { p = lastp, h = a[i] });
                }
            }
        }
        return ans;
    }
}