using System.Collections.Generic;
public static void Main()
Console.WriteLine("Hello World");
Console.WriteLine(HistogramMaximumArea.MaximumAreaOfRectanglesFromHistogramWorst(new int[] { 4, 2, 3, 5, 4 }));
Console.WriteLine(HistogramMaximumArea.MaximumAreaOfRectanglesFromHistogramWorst(new int[] { 4, 2, 3, 5, 4, 3, 3 }));
Console.WriteLine(HistogramMaximumArea.MaximumAreaOfRectanglesFromHistogramBest(new int[] { 4, 2, 3, 5, 4 }));
Console.WriteLine(HistogramMaximumArea.MaximumAreaOfRectanglesFromHistogramBest(new int[] { 4, 2, 3, 5, 4, 3, 3 }));
class HistogramMaximumArea
public static int MaximumAreaOfRectanglesFromHistogramWorst(int[] histogram)
foreach (var rect in histogram)
int maximumWidth = 0, width = 0;
foreach (var innerRect in histogram)
maximumWidth = maximumWidth > width ? maximumWidth : width;
maximumWidth = maximumWidth > width ? maximumWidth : width;
var area = maximumWidth * rect;
maximumArea = maximumArea > area ? maximumArea : area;
public static int MaximumAreaOfRectanglesFromHistogramBest(int[] histogram)
Stack<int> tempStack = new Stack<int>();
for (index = 1; index < histogram.Length; index++)
if (tempStack.Count == 0 || histogram[tempStack.Peek()] <= histogram[index])
var topIndex = tempStack.Peek();
var area = histogram[topIndex] * (index - tempStack.Count - 1);
maximumArea = maximumArea > area ? maximumArea : area;
tempStack.Push(histogram[index]);
while (tempStack.Count > 0)
var topIndex = tempStack.Peek();
var area = histogram[topIndex] * (index - tempStack.Count - 1);