原理解释可以参考以下两篇博客:
http://www.cnblogs.com/avril/archive/2013/08/24/3278873.html
http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
Pick up!捡来的题。看上不不难,自己写了一个最最直观的O(n^2)算法。方法对不对不知道,反正超时了。
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int maxa = 0;
int len = height.size();
for(int i = 0; i < len; i++){
int minh = 100000000;
for(int j = i; j < len; j++){
minh = min(height[j], minh);
maxa = max(maxa, minh * (j - i + 1));
}
}
return maxa;
}
};
int main(){
Solution sol;
int a[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
vector<int> v(a,a+25);
printf("%d\n",sol.largestRectangleArea(v));
}
O(n)的代码如下。似乎技巧性很强,原理没看懂,等有空再手算理解一下。
class Solution:
# @param height, a list of integer
# @return an integer
def largestRectangleArea(self, height):
if len(height) == 1:
return height[0]
height.append(0)
maxArea = 0
stack = []
stp = -1
i = 0
while i < len(height):
if len(stack) == 0 or height[i] >= height[stack[stp]]:
stack.append(i)
stp += 1
i += 1
else:
t = stack[stp]
stack.pop()
stp -= 1
if len(stack) == 0:
maxArea = max(maxArea, height[t] * i)
else:
maxArea = max(maxArea, height[t] * (i - 1 - stack[stp]))
return maxArea
sol = Solution()
print sol.largestRectangleArea([2,1,1,5,1,3])