结果
法一:
法二:
思路
代码
解法一:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size(),res = 0;
for(int i = 0; i < n; ++i){
int left = i,right = i;
while(left >= 0 && heights[left] >= heights[i]) left--;
while(right < n && heights[right] >= heights[i]) right++;
res = (right - left - 1) * heights[i] > res ? (right - left - 1) * heights[i] : res;
}
return res;
}
};
解法二:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if(heights.size() == 0) return 0;
int n = heights.size(),res = heights[0],record;
stack<int> st;
st.push(-1);
for(int i = 0; i < n; ++i){
while(st.top()!=-1 && heights[i] < heights[st.top()]){
int tmp = st.top();
st.pop();
res = max(heights[tmp] * (i - st.top() - 1),res);
}
st.push(i);
}
while(st.top()!=-1){
int tmp = st.top();
st.pop();
res = max(heights[tmp] * (n - st.top() - 1),res);
}
return res;
}
};
后记
She was still too young to know that life never gives anything for nothing, and that a price is always exacted for what fate bestows。