码迷,mamicode.com
首页 > 其他好文 > 详细

0084. Largest Rectangle in Histogram (H)

时间:2021-01-05 10:40:12      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:代码实现   class   i++   html   loading   inf   http   题意   str   

Largest Rectangle in Histogram (H)

题目

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

题意

在直方图中找到面积最大的矩形。

思路

参考[LeetCode] 84. Largest Rectangle in Histogram 直方图中最大的矩形以及LeetCode 笔记系列 17 Largest Rectangle in Histogram


代码实现

Java

class Solution {
    public int largestRectangleArea(int[] heights) {
        int ans = 0;
        Deque<Integer> stack = new ArrayDeque<>();
        int i = 0;
        int[] copy = Arrays.copyOf(heights, heights.length + 1);

        while (i < copy.length) {
            if (stack.isEmpty() || copy[i] > copy[stack.peek()]) {
                stack.push(i++);
            } else {
                int h = copy[stack.pop()];
                int w = stack.isEmpty() ? i : i - stack.peek() - 1;
                ans = Math.max(ans, h * w);
            }
        }

        return ans;
    }
}

0084. Largest Rectangle in Histogram (H)

标签:代码实现   class   i++   html   loading   inf   http   题意   str   

原文地址:https://www.cnblogs.com/mapoos/p/14218788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!