classSolution { public: intlargestRectangleArea(vector<int>& heights){ stack<int> st; int res = 0; int length = heights.size();
for(int i = 0; i < length; i++) { while(!st.empty() && heights[i] < heights[st.top()]) { int index_of_high = st.top(); st.pop(); int left = st.empty() ? -1 : st.top(); res = std::max(res, (i - left -1)*heights[index_of_high]); } st.push(i); }
// 处理剩余的单调元素 1,2,3 index 1,4,5 while(!st.empty()) { int now = st.top(); st.pop(); int before = st.empty() ? -1 : st.top(); res = std::max(res, heights[now] * (length - before - 1)); } return res; } };
classSolution { public: intlargestRectangleArea(vector<int>& heights){ stack<int> st; int res = 0; int length = heights.size();
for(int i = 0; i < length; i++) { while(!st.empty() && heights[i] < heights[st.top()]) { int index_of_high = st.top(); st.pop(); int left = st.empty() ? -1 : st.top(); res = std::max(res, (i - left -1)*heights[index_of_high]); } st.push(i); }
// 处理剩余的单调元素 1,2,3 index 1,4,5 while(!st.empty()) { int now = st.top(); st.pop(); int before = st.empty() ? -1 : st.top(); res = std::max(res, heights[now] * (length - before - 1)); } return res; }