您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Largest Rectangle in Histogram

2012-09-15 00:17 676 查看
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.

public static int LargestRectangleinHistogramOpt(List<int> height)
{
if (height.Count == 0)
return 0;
if (height.Count == 1)
return height[0];

int[] Base = new int[height.Count];
Stack<int> s = new Stack<int>();
int MaxArea = 0;

//Calculate the base from left to right
for (int i = 0; i < height.Count; i++)
{
while(s.Count > 0 && height[i] < height[s.Peek()])
{
Base[s.Peek()] = i - s.Peek();
s.Pop();
}

s.Push(i);
}
while (s.Count > 0)
{
Base[s.Peek()] = height.Count - s.Peek();
s.Pop();
}

//Add base from right to left
for (int i = height.Count - 1; i >= 0; i--)
{
while (s.Count > 0 && height[i] < height[s.Peek()])
{
Base[s.Peek()] += s.Peek() - i - 1;
s.Pop();
}

s.Push(i);
}
while (s.Count > 0)
{
Base[s.Peek()] += s.Peek();
s.Pop();
}

//Find the MaxArea
for (int i = 0; i < height.Count; i++)
{
MaxArea = Math.Max(MaxArea, Base[i] * height[i]);
}

return MaxArea;

}


代码分析:

  上面代码的时间复杂度是O(n)。应该算是比较理想的做法了。

  1. 从左往右计算对应高度右边的底的长度。

  2. 加上从右往左对应高度左边的地的长度。

  3. 通过底×高,计算最大面积

  展开1.

  使用Stack帮助计算。

  例如[2,1,5,6,2,3]

  Base[0,0,0,0,0,0] Stack[ )

    1.i = 0 Base[0,0,0,0,0,0] Stack[0,)

    2.i = 1 下降沿, Base[1,0,0,0,0,0] Stack[0,1,)

    3.i = 2 上升沿, Base[1,0,0,0,0,0] Stack[1,2)

    4.i = 3 上升沿, Base[1,0,0,0,0,0] Stack[1,2,3)

    5.i = 4 下降沿, Base[1,0,2,1,0,0] Satck[1,2,3,4)

    6.i = 5 上升沿, Base[1,0,2,1,0,0] Stack[1,4,5)

    7.把底算完 Base[1,5,2,1,2,1] Stack[1,4,5)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: