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.
For example, Given heights = [2,1,5,6,2,3], return 10.
classSolution { public: intlargestRectangleArea(vector<int> &height){ stack<int> q; int n = height.size(); int ans = 0, curArea; for (int i = 0; i < n; i++){ while (!q.empty() && height[q.top()] >= height[i]){ int h = height[q.top()]; q.pop(); int width = q.empty() ? i : i - 1 - q.top(); if (width * h > ans) ans = h*width; } q.push(i); }
while (!q.empty()){ int h = height[q.top()]; q.pop(); int width = q.empty() ? n : n - 1 - q.top(); if (width * h > ans) ans = h * width; } return ans; } };
classSolution(object): deflargestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ q = [] ans = 0 for i, height inenumerate(heights): while q and heights[q[-1]] > height: h = heights[q.pop()] w = i - 1 - q[-1] if q else i ans = max(ans, h * w) q.append(i) n = len(heights) while q: h = heights[q.pop()] w = n - 1 - q[-1] if q else n ans = max(ans, h * w) return ans
85. Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
classSolution { intlargestRectangleArea(vector<int>& heights){ stack<int> q; int ans = 0, n = heights.size(); for (int i = 0; i < n; ++i) { while (!q.empty() && heights[i] <= heights[q.top()]) { int h = heights[q.top()]; q.pop(); int w = q.empty() ? i : i - 1 - q.top(); if (w * h > ans) ans = w * h; } q.push(i); } while (!q.empty()) { int h = heights[q.top()]; q.pop(); int w = q.empty() ? n : n - 1 - q.top(); if (w * h > ans) ans = w * h; } return ans; }
public: intmaximalRectangle(vector<vector<char>>& matrix){ if (matrix.empty() || matrix[0].empty()) return0;
vector<int> pre_sum(matrix[0].size(), 0); int ans = 0; for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[0].size(); ++j) { pre_sum[j] = matrix[i][j] == '0' ? 0 : pre_sum[j] + 1; } ans = max(ans, largestRectangleArea(pre_sum)); } return ans; } };
classSolution(object): deflargestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ ans = 0 q = [] for i inrange(len(heights)): while q and heights[i] <= heights[q[-1]]: h = heights[q.pop()] w = i - 1 - q[-1] if q else i ans = max(ans, h * w) q.append(i)
while q: h = heights[q.pop()] w = len(heights) - 1 - q[-1] if q elselen(heights) ans = max(ans, h * w) return ans defmaximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ ifnot matrix ornot matrix[0]: return0 pre_sum = [0] * len(matrix[0]) ans = 0 for i inrange(len(matrix)): for j inrange(len(matrix[0])): pre_sum[j] = 0if matrix[i][j] == '0'else pre_sum[j] + 1 ans = max(ans, self.largestRectangleArea(pre_sum)) return ans