84. Largest Rectangle in Histogram

来源:互联网 发布:中文域名重要性 编辑:程序博客网 时间:2024/06/03 15:45

原网址https://leetcode.com/problems/largest-rectangle-in-histogram/description/

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.

代码

class Solution {public:    int largestRectangleArea(vector<int>& heights) {        stack<int> index;        int maxArea = 0;        int i = 0;        while (i < heights.size()) {            if (index.empty() || heights[index.top()] <= heights[i]) {                index.push(i++);            } else {                int j = index.top();                index.pop();                int width = index.empty() ? i : i - index.top() - 1;                maxArea = max(maxArea, heights[j] * width);            }        }                while (!index.empty()) {            int j = index.top();            index.pop();            int width = index.empty() ? i : i - index.top() - 1;            maxArea = max(maxArea, heights[j] * width);        }                return maxArea;    }};


原创粉丝点击