[LeetCode] 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.

clipboard.png

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

clipboard.png

The largest rectangle is shown in the shaded area, which has area = 10 unit.

Solution

class Solution {
    public int largestRectangleArea(int[] height) {
        if (height == null || height.length == 0) return 0;
        int n = height.length;
        int[] left = new int[n];
        int[] right = new int[n];
        right[n-1] = n;
        left[0] = -1;
        for (int i = 1; i < n; i++) {
            int index = i-1;
            while (index >= 0 && height[index] >= height[i]) index = left[index];
            left[i] = index;
        }
        for (int i = n-2; i >= 0; i--) {
            int index = i+1;
            while (index < n && height[index] >= height[i]) index = right[index];
            right[i] = index;
        }
        int max = 0;
        for (int i = 0; i < n; i++) max = Math.max(max, height[i]*(right[i]-left[i]-1));
        return max;
    }
}
阅读 738

推荐阅读
Road to Glory
用户专栏

對酒當歌,人生幾何?譬如朝露,去日苦多。

22 人关注
639 篇文章
专栏主页