棋子

导航

largest rectangle in histogram leetcode

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.

思路分析:暴力破解方法应该不需要多说,直接计算每一个元素所能构成的最大矩形面积,并与max比较并记录。

这道题,是看了网上的众多博客之后结合自己的理解来mark一下这个过程(最主要是一遍就解决了,时间复杂度O(n)):

  用到了栈,栈顶元素,跟当前索引是关键:

    入栈:如果栈为空或者栈顶元素(其在直方图中的对应高度)小于等于当前索引(对应高度),这样就使得,栈中的元素(对应高度)是非递减的。这样符合贪心算法的思想,因为若是当前索引(对应高度)大于栈顶元素(对应高度),则继续入栈,因为必然能得到更大的矩形面积,贪心!

    出栈:当前索引(对应高度)<栈顶元素(对应高度),则栈顶元素出栈,并记录下其对应高度,并计算其能对应的最大矩形面积。注意一个关键点:栈顶元素跟当前索引之间的所有元素(对应高度)都大于等于这两个端点对应高度!

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int>& height) {
 4         stack<int> sta;
 5         height.push_back(0);
 6         int i = 0,sum=0;
 7         while (i < height.size())
 8         {
 9             if (sta.empty() ||height[sta.top()] <= height[i])
10             {
11                 sta.push(i++);
12             }
13             else
14             {
15                 int t = sta.top();
16                 sta.pop();
17                 sum = max(sum, height[t]*(sta.empty()?i:i - sta.top() - 1));
18             }
19         }
20         return sum;
21     }
22 };

 

posted on 2015-08-22 20:05  鼬与轮回  阅读(196)  评论(0编辑  收藏  举报