您的位置:首页 > 其它

Largest Rectangle in Histogram

2013-05-20 15:56 225 查看
解题思路:以每个柱子作为高, 向左右搜出最大的宽度,会求出n个值, 从而这n个值中的最大值就是结果。

直接贴代码后超时, 受帖子/article/5158301.html启发,剪枝后AC。

public class Solution {
public int bound;

public int largestRectangleArea(int[] height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int max = 0;
int len = height.length;
bound = 0;
for (int i = 0; i < len; i++)
bound += height[i];

for (int i = len - 1; i >= 0; i--) {
if (bound > max) {
int wide = 1;
for (int j = i - 1; j >= 0; j--)
if (height[j] >= height[i])
wide++;
else
break;
for (int j = i + 1; j < len; j++)
if (height[j] >= height[i])
wide++;
else
break;

int tem = height[i] * wide;
if (tem > max)
max = tem;
}
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: