84. Largest Rectangle in Histogram

Problem:

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.

Example:

Input: [2,1,5,6,2,3]
Output: 10

思路

Solution (C++):

int largestRectangleArea(vector<int>& heights) {
    heights.push_back(0);
    int max_area = 0, n = heights.size();
    vector<int> index;
    
    for (int i = 0; i < n; ++i) {
        while (!index.empty() && heights[i] <= heights[index.back()]) {
            int h = heights[index.back()];
            index.pop_back();
            
            int j = index.empty() ? -1 : index.back();
            max_area = max(max_area, (i-j-1) * h);
        }
        index.push_back(i);
    }
    return max_area;
}

性能

Runtime: 8 ms  Memory Usage: 10.6 MB

posted @ 2020-02-16 10:17  littledy  阅读(85)  评论(0)    收藏  举报