minLeftIndexes[0] = -1; // 统计每根柱子左侧最近且低于自己的柱子 for (int i = 1; i < heights.size(); i++) { int t = i - 1; while (t >= 0 && heights[t] >= heights[i]) t = minLeftIndexes[t]; minLeftIndexes[i] = t; }
minRightIndexes.back() = heights.size(); // 统计每根柱子右侧最近且低于自己的柱子 for (int i = heights.size() - 1; i >= 0; i--) { int t = i + 1; while (t < heights.size() && heights[t] >= heights[i]) t = minRightIndexes[t]; minRightIndexes[i] = t; }
int result = 0; // 求左右两侧高于等于自己的柱子以自己的高所能形成的面积 for (int i = 0; i < heights.size(); i++) { int sum = heights[i] * (minRightIndexes[i] - minLeftIndexes[i] - 1); result = max(sum, result); } return result; } };
classSolution { public: intlargestRectangleArea(vector<int>& heights){ int result = 0; stack<int> st; heights.insert(heights.begin(), 0); heights.push_back(0); st.push(0);
for (int i = 1; i < heights.size(); i++) { if (heights[i] >= heights[st.top()]) { st.push(i); } else { while (!st.empty() && heights[i] < heights[st.top()]) { int mid = st.top(); st.pop(); if (!st.empty()) { int left = st.top(); int right = i; int w = right - left - 1; int h = heights[mid]; result = max(result, w * h); } } st.push(i); } } return result; } };