给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。
图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。
示例:
输入: [2,1,5,6,2,3]
输出: 10
dp不是最优解,stack是最优解
class Solution {
int maxarea=0;
public int largestRectangleArea(int[] heights) {
return calculate( heights,0,heights.length-1);
}
public int calculate(int[] heights,int start,int end){
if (start>end) return 0;
int small=heights[start];
int index=start;
for(int i=start;i<=end;i++){
if(heights[i]<small){
small=heights[i];
index=i;
}
}
return Math.max((end-start+1)*small,Math.max(calculate(heights, start,index - 1), calculate(heights,index + 1, end)));
}
}
409

被折叠的 条评论
为什么被折叠?



