LeetCode 84. Largest Rectangle in Histogram

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.

image.png

Stack Solution

  • 对每个数来说,到array中下一个比它小的数位置的长度就是rectangle的width,所以在stack中放入array的index,然后当stack顶的数比它大时,计算rectangle面积
  • 如果最后一段是递增的话,就会没有得到处理,所以在最后加上0来处理最后一段数据
  • Time complexity: O(n)
class Solution {
    public int largestRectangleArea(int[] heights) {
        int maxVal = 0;
        Stack<Integer> stack = new Stack<Integer>();
        for (int i=0; i<=heights.length; i++) {
            int h = i == heights.length ? 0 : heights[i];
            while (! stack.isEmpty() && heights[stack.peek()] > h) {
                int height = heights[stack.pop()];
                int start = stack.isEmpty() ? -1 : stack.peek();
                maxVal = Math.max(maxVal, height * (i - start - 1));
            }
            stack.push(i);
        }
        return maxVal;
    }
}

Divide and conquer Solution

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容