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;
using System.Collections.Generic;

namespace DPL3_C_Largest_Rectangle_in_a_Histogram
{
	class Program
	{
		const int Sentinel = -1;

		static void Main ( string[] args )
		{
			int count = int.Parse (Console.ReadLine ());
			List<int> input = new List<int> (Array.ConvertAll (Console.ReadLine ().Split (' '), int.Parse));
			input.Add (Sentinel);

			Stack<Rectangle> stack = new Stack<Rectangle> (count);
			long maxArea = 0;

			for (int lp = 0; lp <= count; lp++)
			{
				Rectangle rect = new Rectangle (input[lp], lp);

				//1.スタックが空の場合
				if (stack.Count == 0)
				{
					//スタックにrectを追加する
					stack.Push (rect);
				}
				//2.rectの高さがスタックのトップより高い場合
				else if (stack.Peek ().Height < rect.Height)
				{
					//スタックに追加する
					stack.Push (rect);
				}
				//3.等しい場合
				else if (stack.Peek ().Height == rect.Height)
				{
					//Nothing
				}
				//4.rectの高さがスタックのトップより低い場合
				else if (stack.Peek ().Height > rect.Height)
				{
					Rectangle previousRect = null;

					//スタックが空ではなく、スタックのトップの高さがrectの高さ未満になるまで
					do
					{
						//スタックから取り出し面積を更新する
						previousRect = stack.Pop ();
						long size = lp - previousRect.Position;
						long area = previousRect.Height * size;

						maxArea = Math.Max (maxArea, area);

					} while (stack.Count != 0 && stack.Peek ().Height >= rect.Height);

					//スタックに追加する
					//ただし、positionは最後にスタックから取り出した長方形のpositionと同じにする
					rect = new Rectangle (rect.Height, previousRect.Position);
					stack.Push (rect);
				}
			}

			Console.WriteLine (maxArea);
		}
	}

	class Rectangle
	{
		public Rectangle ( int height, int position )
		{
			this.Height = height;
			this.Position = position;
		}

		public int Height { private set; get; }
		public int Position { private set; get; }
	}
}