【算法刷题】 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 =10unit.

 

For example,
Given height =[2,1,5,6,2,3],
return10

 

理解参考

自己的理解在笔记本里,先贴上代码

    int largestRectangleArea(vector &height) {
		if (height.empty())
			return 0;
		
		int maxArea(0);
		stack st;
		int i(0);
		int len = height.size();
		while (i=height[st.top()])
			{
				st.push(i);
				++i;
			}
			else
			{
				int ntop = height[st.top()];
				st.pop();
				
				int Area = ntop*(st.empty() ? i : (i - st.top() - 1));
				maxArea = max(Area, maxArea);
			}
		}
        
		while (!st.empty())
		{
			int ntop = height[st.top()];
			st.pop();

			int Area = ntop*(st.empty() ? i : (i - st.top() - 1));
			maxArea = max(Area, maxArea);
		}

		return maxArea;
        
    }

 

你可能感兴趣的:(算法题)