Largest Rectangle in Histogram(LeetCode)

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.

Example:

Input: [2,1,5,6,2,3]
Output: 10
 
 

思路:

对于每一个bar,找到右边大于等于这个bar高的个数,再找到左边大于等于这个bar高的个数,这两个个数的和就是矩形的长,矩形的高是这个bar的高度。

这个方法的时间复杂度较高。

class Solution {
public:
	int largestRectangleArea(vector<int>& heights) {
		if(heights.empty())
			return 0;
		int n = heights.size();
		vector<int> area;
		for(int i=0;i<n;i++){
			int j=i;
			int length=0;
			while(j<n && heights[i]<=heights[j]){
				length++;
				j++;
			}
			int k=i-1;
			while(k>=0 && heights[i]<=heights[k]){
				length++;
				k--;
			}
			area.push_back(heights[i]*length);
		}
		int max_area= *max_element(area.begin(),area.end());
		return max_area;
	}
};

猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80306247