84. Largest Rectangle in Histogram
https://leetcode.com/problems/largest-rectangle-in-histogram/description/
Last updated
https://leetcode.com/problems/largest-rectangle-in-histogram/description/
Last updated
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
s, res = [], 0
heights.append(0)
for i, h in enumerate(heights):
while len(s) > 0 and h < heights[s[-1]]:
hei = heights[s[-1]]
s.pop()
wid = i - s[-1] - 1 if len(s) > 0 else i
res = max(res, hei * wid)
s.append(i)
return res/*
* @lc app=leetcode id=84 lang=cpp
*
* [84] Largest Rectangle in Histogram
*/
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> ind;
heights.push_back(0);
int res = 0;
for (int i = 0; i < heights.size(); ++i) {
while (!ind.empty() && heights[ind.top()] > heights[i]) {
const int h = heights[ind.top()];
ind.pop();
const int w = ind.empty() ? i : i - ind.top() - 1;
res = max(res, h * w);
}
ind.push(i);
}
return res;
}
};