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.

84. Largest Rectangle in Histogram_第1张图片
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

84. Largest Rectangle in Histogram_第2张图片
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& heights) {
    heights.push_back(0);
    int max_area = 0, n = heights.size();
    vector 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

你可能感兴趣的:(84. Largest Rectangle in Histogram)