1. 程式人生 > >【LeetCode】84. Largest Rectangle in Histogram(C++)

【LeetCode】84. Largest Rectangle in Histogram(C++)

地址:https://leetcode.com/problems/largest-rectangle-in-histogram/

題目:

Given n 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

理解:

給了一個柱狀圖,要求其能構成的矩形的最大面積。構成的矩形不能超過其起始任意一個矩形的高。也就是說,矩形的高是受限於高度最矮的矩形的。

覺得這個題和Container With Most Water

有一點點相似。不過區別在於那個題,容量只受限於左右兩個邊中較低的,而本題中,是受限於一個區域中最矮的矩形。

實現:

參考:Largest Rectangular Area in a Histogram
藉助了一個棧,儲存比當前矮的位置。i為工作指標
如果heights[i]大於等於棧頂,就把其入棧;
如果小於,則依次彈出棧頂,並用彈出的值當作當前矩形的高,i-1為矩形的右邊界,而把新的棧頂+1作為左邊界。如果棧為空,就說明沒有更矮的了,直接把0作為左邊界就可以了。

class Solution {
public:
	int largestRectangleArea(vector<
int>& heights) { int maxArea = 0; stack<int> stk; for (int i = 0; i <= heights.size(); i++) { int h = (i == heights.size() ? 0 : heights[i]); if (stk.empty() || h >= heights[stk.top()]) stk.push(i); else { int heightIndex = stk.top(); stk.pop(); int r = i - 1; int l = stk.empty() ? 0 : stk.top()+1; int width = r - l + 1; maxArea = max(maxArea, heights[heightIndex] * width); i--; } } return maxArea; } };