1. 程式人生 > >尋找直方圖中的最大矩形 Largest Rectangle in Histogram

尋找直方圖中的最大矩形 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.For example,Given height = [2,1,5,6,2,3],return 10.

思路:矩形的高度瓶頸在於最小的高度。順序掃描陣列元素,同時在棧中維護一個遞增的序列。當棧為空或是遇到比棧頂元素大的元素時,則認為瓶頸還未到來,只入棧而不計算;當遇到比棧頂元素小的元素時,則認為到達一個瓶頸,則對瓶頸左側的矩形進行清算。

當掃描完畢後,再對棧中遺留下的元素進行清算。 

該方法的時間複雜度O(N),空間複雜度O(N)。

class Solution {
	public:
		int max(int a, int b)
		{
			if(a > b)
				return a;
			else
				return b;
		}
		int largestRectangleArea(vector<int> &height) {
			stack<int> s; //注意棧中存的是下標
			int len = height.size();
			int maxs = 0;
			int k;
			for(int i=0; i<len; i++)
			{
				if(s.empty() || height[s.top()] <= height[i])
					s.push(i);
				else
				{
					while(!s.empty() && height[s.top()] > height[i])
					{
						k = s.top();
						s.pop();
						if(s.empty()) //注意時刻防止棧為空
							maxs = max(maxs, i*height[k]);
						else
							maxs = max(maxs, (i-s.top()-1)*height[k]);
					}
					s.push(i);
				}
			}
			while(!s.empty())
			{
				k = s.top();
				s.pop();
				if(s.empty()) //注意時刻防止棧為空
					maxs = max(maxs, len*height[k]);
				else
					maxs = max(maxs, (len-s.top()-1)*height[k]);
			}
			return maxs;
		}
};