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

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.

 1         public static int LargestRectangleinHistogramOpt(List<int> height)

 2         {

 3             if (height.Count == 0)

 4                 return 0;

 5             if (height.Count == 1)

 6                 return height[0];

 7 

 8             int[] Base = new int[height.Count];

 9             Stack<int> s = new Stack<int>();

10             int MaxArea = 0;

11 

12             //Calculate the base from left to right

13             for (int i = 0; i < height.Count; i++)

14             {

15                 while(s.Count > 0 && height[i] < height[s.Peek()])

16                 {

17                     Base[s.Peek()] = i - s.Peek();

18                     s.Pop();

19                 }

20 

21                 s.Push(i);

22             }

23             while (s.Count > 0)

24             {

25                 Base[s.Peek()] = height.Count - s.Peek();

26                 s.Pop();

27             }

28 

29             //Add base from right to left

30             for (int i = height.Count - 1; i >= 0; i--)

31             {

32                 while (s.Count > 0 && height[i] < height[s.Peek()])

33                 {

34                     Base[s.Peek()] += s.Peek() - i - 1;

35                     s.Pop();

36                 }

37 

38                 s.Push(i);

39             }

40             while (s.Count > 0)

41             {

42                 Base[s.Peek()] += s.Peek();

43                 s.Pop();

44             }

45 

46             //Find the MaxArea

47             for (int i = 0; i < height.Count; i++)

48             {

49                 MaxArea = Math.Max(MaxArea, Base[i] * height[i]);

50             }

51 

52             return MaxArea;

53 

54         }

代码分析:

  上面代码的时间复杂度是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)

你可能感兴趣的:(LeetCode)