[Leetcode] #84 Largest Rectangle in Histogram

来源:互联网 发布:招商银行网络中心校招 编辑:程序博客网 时间:2024/04/30 15:18

Discription:

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 heights = [2,1,5,6,2,3],
return 10.

Solution:

int largestRectangleArea(vector<int>& heights) {if (heights.empty()) return 0;int result = 0;stack<int> stk;stk.push(heights[0]);for (int i = 1; i < heights.size(); i++){if (heights[i] >= stk.top()){stk.push(heights[i]);}else{int len = 0;while (!stk.empty() && stk.top()>heights[i]){len++;int temp = stk.top()*len;if (temp > result)result = temp;stk.pop();}for (int j = 0; j <= len; j++)stk.push(heights[i]);}}for (int i = 0; i < heights.size(); i++){int temp = stk.top()*(i + 1);if (temp>result)result = temp;stk.pop();}return result;}
详细解释请参考:http://blog.csdn.net/fly_yr/article/details/50372344

0 0
原创粉丝点击