您的位置:首页 > 其它

直方图最大矩形覆盖-LintCode

2017-07-20 09:42 253 查看
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.

样例

给出 height = [2,1,5,6,2,3],返回 10

一刷TLE(捂脸)

#ifndef C122_H
#define C122_H
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
int largestRectangleArea(vector<int> &height) {
// write your code here
if (height.size() == 0)
return 0;
return largestAreaRecur(height, 0,highVal(height));
}
int largestAreaRecur(vector<int> &v, int i,int k)
{
int len = v.size();
int num = 0,count=0;
if (i > k)
return 0;
for (int j = 0; j < len ; ++j)
{
if (v[j] >= 0)
{
num++;
}
else
{
count = maxVal(count, num);
num = 0;
}
}
count = maxVal(num, count);
for (auto &c : v)
{
c--;
}
return maxVal(i*count,largestAreaRecur(v,i+1,k));
}
int maxVal(int a, int b)
{
return a>b ? a : b;
}
int highVal(vector<int> v)
{
int num = 0;
for (auto c : v)
{
num = c > num ? c : num;
}
return num;
}
};
#endif


another

#ifndef C122_H
#define C122_H
#include<iostream>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
class Solution {
public:
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
int largestRectangleArea(vector<int> &height) {
// write your code here
int res = 0;
stack<int> s;
height.push_back(0);
for (int i = 0; i < height.size(); ++i) {
if (s.empty() || height[s.top()] < height[i]) s.push(i);
else {
int cur = s.top();
s.pop();
res = max(res, height[cur] * (s.empty() ? i : (i - s.top() - 1)));
--i;
}
}
return res;
}
};
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: