LeetCode: Largest Rectangle in Histogram

Problem:

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.

利用单调队列,用两个数组l[i]和r[i]表示第i个矩形可以向左和向右扩展的最远距离。

class Solution {
public:
    int largestRectangleArea(vector &height) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int nSize = height.size();
        if (nSize == 0) return 0;
        
        int* l = new int[nSize];
        int* r = new int[nSize];
        l[0] = 0;
        r[nSize-1] = nSize - 1;
        for (int i = 1; i < nSize; ++i)
        {
            int j = i;
            while(j > 0 && height[i] <= height[j-1])
                j = l[j-1];
            l[i] = j;
        }
        
        for(int i = nSize-2; i >= 0; --i)
        {
            int j = i;
            while(j < nSize - 1 && height[i] <= height[j+1])
                j = r[j+1];
            r[i] = j;
        }
        
        int max = 0;
        for (int i = 0; i < nSize; ++i)
        {
            int ar = (r[i] - l[i] + 1) * height[i];
            max = max > ar ? max : ar;   
        }
        return max;
    }
};


你可能感兴趣的:(算法,C++)