Leetcode: Largest Rectangle in Histogram

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.

For example,
Given height = [2,1,5,6,2,3],
return 10.

以前在陈立人的微博上看到过,断断续续加起来鼓捣了一个半个小时。有待努力啊!

#include <vector>
#include <stack>

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        if (height.empty()) {
            return 0;
        }
        
        int i = 0;
        int largest = 0;
        // pair->first: index, pair->second: height
        stack<pair<int, int>> area_stack;
        area_stack.push(make_pair(0, -1));
        for (; i < height.size(); i++) {
            auto top = area_stack.top();
            if (height[i] >= top.second) {
                area_stack.push(make_pair(i, height[i]));
            }
            else {
                int pre_index;
                do {
                    pre_index = top.first;
                    int area = top.second * (i - pre_index);
                    if (area > largest) {
                        largest = area;
                    }
                    area_stack.pop();
                    top = area_stack.top();
                } while (top.second != -1 && height[i] <= top.second);
                area_stack.push(make_pair(pre_index, height[i]));
            }
        }
        
        while (!area_stack.empty()) {
            auto top = area_stack.top();
            int area = top.second * (i - top.first);
            if (area > largest) {
                largest = area;
            }
            area_stack.pop();
        }
        
        return largest;
    }
};

只存Index。

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        int max_area = 0;
        stack<int> indices;
        int top_index, area;
        int i = 0;
        while (i < height.size()) {
            if (indices.empty() || height[indices.top()] <= height[i]) {
                indices.push(i++);
            }
            else {
                top_index = indices.top();
                indices.pop();
                area = height[top_index] * (indices.empty() ? i : i - indices.top() - 1);
                max_area = max(max_area, area);
            }
        }
        
        while (!indices.empty()) {
            top_index = indices.top();
            indices.pop();
            area = height[top_index] * (indices.empty() ? i : i - indices.top() - 1);
            max_area = max(max_area, area);
        }
        
        return max_area;
    }
};


你可能感兴趣的:(LeetCode)