Given an array of integers heights representing the histogram’s bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Example 1:
Input: heights = [2,1,5,6,2,3] Output: 10 Explanation: The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units.
/** * @param {number[]} heights * @return {number} */ var largestRectangleArea = function(heights) { // corner case if (heights == null || heights.length == 0) { return0; }
// normal case let stack = []; let res = 0; for (let i = 0; i <= heights.length; i++) { let h = i == heights.length ? 0 : heights[i]; while (stack.length && h < heights[stack[stack.length - 1]]) { let height = heights[stack.pop()]; let start = !stack.length ? -1 : stack[stack.length - 1]; let area = height * (i - start - 1); res = Math.max(res, area); } stack.push(i); } return res; };
其他思路
暴力解,O(n^2),OA也勉强能过,不会超时 Java实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { publicintlargestRectangleArea(int[] heights) { intlen= heights.length; intarea=0; // 枚举左边界 for (intleft=0; left < len; left++) { intminHeight= Integer.MAX_VALUE; // 枚举右边界 for (intright= left; right < len; right++) { // 确定高度,我们要最小的高度 minHeight = Math.min(minHeight, heights[right]); // 计算面积,我们要保留计算过的最大的面积 area = Math.max(area, (right - left + 1) * minHeight); } } return area; } }
相关题目
1 2 3 4 5
84. Largest Rectangle in Histogram 85. Maximal Rectangle 221. Maximal Square 1277. Count Square Submatrices with All Ones 1727. Largest Submatrix With Rearrangements