解题思路

这是一道使用单调栈解决的经典问题,主要思路如下:

  1. 问题分析:

    • 给定一个直方图,每个柱子宽度为1
    • 需要找到直方图中最大的矩形面积
    • 矩形可以横跨多个柱子
  2. 解决方案:

    • 使用单调栈维护递增的高度
    • 当遇到更低的柱子时,计算当前可能的最大矩形
    • 通过栈来找到左右边界
  3. 关键点:

    • 在数组末尾添加高度0作为哨兵
    • 利用栈顶元素计算矩形的高度
    • 利用栈来确定矩形的宽度

代码

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        // 添加哨兵
        heights.push_back(0);
        stack<int> st;
        int maxArea = 0;
        
        for (int i = 0; i < heights.size(); i++) {
            // 当栈不为空且当前高度小于栈顶高度时
            while (!st.empty() && heights[i] < heights[st.top()]) {
                int height = heights[st.top()];
                st.pop();
                
                // 计算宽度
                int width = i;
                if (!st.empty()) {
                    width = i - st.top() - 1;
                }
                
                // 更新最大面积
                maxArea = max(maxArea, height * width);
            }
            st.push(i);
        }
        
        return maxArea;
    }
};
import java.util.*;

class Solution {
    public int largestRectangleArea(int[] heights) {
        // 创建新数组并添加哨兵
        int[] newHeights = new int[heights.length + 1];
        System.arraycopy(heights, 0, newHeights, 0, heights.length);
        newHeights[heights.length] = 0;
        
        Stack<Integer> stack = new Stack<>();
        int maxArea = 0;
        
        for (int i = 0; i < newHeights.length; i++) {
            while (!stack.isEmpty() && newHeights[i] < newHeights[stack.peek()]) {
                int height = newHeights[stack.pop()];
                
                int width = i;
                if (!stack.isEmpty()) {
                    width = i - stack.peek() - 1;
                }
                
                maxArea = Math.max(maxArea, height * width);
            }
            stack.push(i);
        }
        
        return maxArea;
    }
}
class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        # 添加哨兵
        heights.append(0)
        stack = []
        max_area = 0
        
        for i in range(len(heights)):
            # 当栈不为空且当前高度小于栈顶高度时
            while stack and heights[i] < heights[stack[-1]]:
                height = heights[stack.pop()]
                
                # 计算宽度
                width = i
                if stack:
                    width = i - stack[-1] - 1
                    
                # 更新最大面积
                max_area = max(max_area, height * width)
            
            stack.append(i)
            
        return max_area

算法及复杂度

  • 算法:单调栈
  • 时间复杂度: - 每个元素最多入栈出栈一次
  • 空间复杂度: - 需要一个栈来存储索引