xinyu04

导航

LeetCode Largest Rectangle in Histogram 思维

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.

Solution

很容易知道答案为

\[\max_{i,j}(|i-j|\times \min_{i\leq k\leq j} h[k]) \]

所以对于每个位置,我们可以先预处理得到该位置覆盖的最左右端点。这里有个tip,我们可以不断的 \(jump\) 来得到每个位置的左右端点,而不需要 \(O(n^2)\) 的复杂度

点击查看代码
class Solution {
private:
    int ans = -1;
    int left_lowest_idx[100002];
    int right_lowest_idx[100002];
    
    
public:
    int largestRectangleArea(vector<int>& heights) {
        int n = heights.size();
        
        left_lowest_idx[0] = -1;
        right_lowest_idx[n-1]=n;
        
        for(int i=1;i<n;i++){
            int p = i-1;
            while(p>=0 && heights[p]>=heights[i]){
		// jump
                p = left_lowest_idx[p];
            }
            left_lowest_idx[i] = p;
            //cout<<p<<endl;
        }
        
        for(int i=n-1;i>=0;i--){
            int p = i+1;
            while(p<n && heights[p]>=heights[i]){
                p = right_lowest_idx[p];
            }
            right_lowest_idx[i] = p;
        }
        
        for(int i=0;i<n;i++){
            //cout<<right_lowest_idx[i]<<" "<<left_lowest_idx[i]<<endl;
            ans = max(ans, heights[i]*(right_lowest_idx[i]-left_lowest_idx[i]-1));
        }
        return ans;
    }
};

posted on 2022-07-15 22:17  Blackzxy  阅读(13)  评论(0编辑  收藏  举报