LeetCode | 84. 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.

 

Example:

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

 

代碼:

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int maxS = 0;
		int num = heights.size();
		vector<int> left(num + 1, 0);
		vector<int> right(num + 1, num);
		left[0] = -1;
		right[num - 1] = num;
		for (int i = 0; i < num; i++)
		{
			int j = i - 1;
			for (; j >= 0 && heights[j] >= heights[i]; j = left[j]);
			left[i] = j;
		}
		for (int i = num - 1; i >= 0; i--)
		{
			int j = i + 1;
			for (; j < num && heights[j] >= heights[i]; j = right[j]);
			right[i] = j;
		}
		for (int i = 0; i < num; i++)
		{
			maxS = max(maxS, (right[i] - left[i] - 1)*heights[i]);
		}
		return maxS;
    }
};

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章