LeetCode 84. Largest Rectangle i

2018-11-05  本文已影响0人  manayuan

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

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

上一篇 下一篇

猜你喜欢

热点阅读