Leetcode-84. Largest Rectangle in Histogram [C++][Java]

Leetcode-84. Largest Rectangle in Histogramhttps://leetcode.com/problems/largest-rectangle-in-histogram/description/

一、题目描述

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Example 1:

Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.

Example 2:

Input: heights = [2,4]
Output: 4

Constraints:

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^4

二、解题思路

单调栈+动态规划

  • 时间复杂度为 O(mn)

  • 空间复杂度为 O(n)

【C++】

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int n = heights.size();
        if (n == 0) {
            return 0;
        }
        int res = 0;
        vector<int> left(n, -1), right(n, n);
        stack<int> st;
        for (int j = 0; j < n; ++j) {
            while (!st.empty() && heights[st.top()] >= heights[j]) {
                right[st.top()] = j;
                st.pop();
            }
            if (!st.empty()) {
                left[j] = st.top();
            }
            st.push(j);
        }
        for (int j = 0; j < n; ++j) {
            res = max(res, heights[j] * (right[j] - left[j] - 1));
        }
        return res;
    }
};

【Java】

class Solution {
    public int largestRectangleArea(int[] heights) {
        if (heights == null || heights.length == 0) {
            return 0;
        }
        int n = heights.length, res = 0;
        int[] left = new int[n];
        int[] right = new int[n];
        Arrays.fill(left, -1);
        Arrays.fill(right, n);
        Stack<Integer> st = new Stack<>();
        for (int j = 0; j < n; j++) {
            while (!st.isEmpty() && heights[st.peek()] >= heights[j]) {
                right[st.pop()] = j;
            }
            if (!st.isEmpty()) {
                left[j] = st.peek();
            }
            st.push(j);
        }
        for (int j = 0; j < n; j++) {
            res = Math.max(res, heights[j] * (right[j] - left[j] - 1));
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值