2023.8.30

本题和接雨水 有点类似,依旧用双指针来解。但是本题要记录的是当前柱子 左右两侧第一个小于该柱子的索引。将其保存在两个数组中,最后再求最大面积。代码如下:
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        vector<int> min_left_index(heights.size()); //记录当前柱子 左侧第一个小于该柱子的索引
        vector<int> min_right_index(heights.size()); //记录当前柱子 右侧第一个小于该柱子的索引
        min_left_index[0] = -1;
        for(int i=1; i<heights.size(); i++)
        {
            int temp = i-1;
             while(temp>=0 && heights[temp]>=heights[i]) 
             {
                 temp = min_left_index[temp];
             }
             min_left_index[i] = temp;
        }
        min_right_index[heights.size()-1] = heights.size();
        for(int i=heights.size()-2; i>=0; i--)
        {
            int temp = i+1;
            while(temp<=heights.size()-1 && heights[temp]>=heights[i])
            {
                temp = min_right_index[temp];
            }
            min_right_index[i] = temp;
        }
        //求最大面积
        int ans = 0;
        for(int i=0; i<heights.size(); i++)
        {   
            ans = max(ans , heights[i]*(min_right_index[i]-min_left_index[i]-1));
        }
        return ans;
    }
};



















