题目:
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
Example:
Input: [2,1,5,6,2,3] Output: 10
代码:
1——递归方法,较慢
class Solution {
public:
int calmin(vector<int>& height, int i, int j) {
int index = -1;
int min = INT_MAX;
for (int m = i; m <= j; m++) {
if (height[m] < min) {
min = height[m];
index = m;
}
}
return index;
}
int helper(vector<int>& height, int i, int j) {
if (i > j)return 0;
if (i == j)return height[i];
int index = calmin(height, i, j);
int area = (j - i + 1)*height[index];
int leftarea = helper(height, i, index - 1);
int rightarea = helper(height, index + 1, j);
int res = max({ area,leftarea,rightarea });
return res;
}
int largestRectangleArea(vector<int>& heights) {
int i = 0, j = heights.size() - 1;
return helper(heights, i, j);
}
};
2——遍历,所有面积遍历一遍然后存起来
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0;
for (int i = 0; i < heights.size(); ++i) {
if (i + 1 < heights.size() && heights[i] <= heights[i + 1]) {
continue;
}
int minH = heights[i];
for (int j = i; j >= 0; --j) {
minH = min(minH, heights[j]);
int area = minH * (i - j + 1);
res = max(res, area);
}
}
return res;
}
};
想法:
多动脑子