Leetcode 84. Largest Rectangle in Histogram

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 84. Largest Rectangle in Histogram_第1张图片
Largest Rectangle in Histogram

2. Solution

  • O(N^2)
class Solution {
public:
    int largestRectangleArea(vector& heights) {
        int maxArea = 0;
        for(int i = 0; i < heights.size(); i++) {
            int left = i;
            int right = i;
            for(left = i; left >= 0; left--) {
                if(heights[left] < heights[i]) {
                    break;
                }
            }
            for(right = i; right < heights.size(); right++) {
                if(heights[right] < heights[i]) {
                    break;
                }
            }
            int area = (right - 1 - left - 1 + 1) * heights[i];
            if(area > maxArea) {
                maxArea = area;
            }
        }
        return maxArea;
    }
};
  • O(N)
class Solution {
public:
    int largestRectangleArea(vector& heights) {
        int maxArea = 0;
        stack border;
        heights.push_back(0);
        for(int i = 0; i < heights.size(); i++) {
            if(border.empty() || heights[i] > heights[border.top()]) {
                border.push(i);
            }
            else {
                int index = border.top();
                border.pop();
                int area = heights[index] * (border.empty()?i:i - border.top() - 1);
                if(area > maxArea) {
                    maxArea = area;
                }
                i--;
            }
        }
        return maxArea;
    }
};

Reference

  1. https://leetcode.com/problems/largest-rectangle-in-histogram/description/

你可能感兴趣的:(Leetcode 84. Largest Rectangle in Histogram)