Approach
For each value in the vector, we need to find the first one that is smaller than it in the left (and right), and this can be done with mono-stack. So we maintain a mono-stack and record the first index smaller than it on the left (and right) hand side, and in the end right-left-1 times the current value is the maximum profit for this position.
Code
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.insert(heights.begin(), INT_MIN);
heights.insert(heights.end(), INT_MIN);
int n = heights.size();
vector<int> left(n, -1);
vector<int> right(n, -1);
{
stack<int> stk;
stk.push(0);
for(int i = 1 ; i < n-1 ; ++i) {
while(!stk.empty()) {
int prevIdx = stk.top();
if(heights[prevIdx] >= heights[i]) {
stk.pop();
} else {
left[i] = prevIdx;
stk.push(i);
break;
}
}
}
}
{
stack<int> stk;
stk.push(n-1);
for(int i = n-2 ; i >= 0 ; --i) {
while(!stk.empty()) {
int prevIdx = stk.top();
if(heights[prevIdx] >= heights[i]) {
stk.pop();
} else {
right[i] = prevIdx;
stk.push(i);
break;
}
}
}
}
// calculate
int prof = INT_MIN;
for(int i = 1 ; i < n-1 ; ++i) {
prof = max(prof, (right[i]-left[i]-1)*heights[i]);
}
return prof;
}
};