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.post
For example,
Given heights = [2,1,5,6,2,3]
,
return 10
.spa
這道題最直接的方法就是暴力搜索了,從第一個方塊開始,向前向後一直搜索到比它高度小的方塊爲止,而後更新最大面積,這種方法的時間複雜度是O(n^2)。code
有沒有更好的方法呢?答案是有的。藉助於stack這一數據結構,能夠實現一個O(n)的算法,具體思路以下。blog
stack中存儲的是方塊的下標索引號,若是當前方塊的高度大於等於棧頂元素對應方塊的高度,那麼就將該方塊的索引號進棧。索引
不然(即當前方塊高度更小時),則說明繼續劃分下去會產生鏤空區域,所以咱們將棧頂元素一次出棧,每次出棧時都計算一下以該棧頂元素爲高度基準時,劃分出的面積大小。it
這樣這個算法複雜度就下降到了O(n),具體請看代碼。io
class Solution { public: int largestRectangleArea(vector<int>& heights) { if (heights.size() == 0) { return 0; } stack<int> index; int res = 0, i = 0; while (i < heights.size()) { if (index.empty() || heights[index.top()] <= heights[i]) { index.push(i++); } else { int top = heights[index.top()]; index.pop(); int size = top * (index.empty() ? i : i - index.top() - 1); res = max(res, size); } } while (index.size()) { int top = heights[index.top()]; index.pop(); int size = top * (index.empty() ? i : i - index.top() - 1); res = max(res, size); } return res; } };