For example,
Given height = [2,1,5,6,2,3]
,
return 10
.
解题思路:
参考Problem H: Largest Rectangle in a Histogram第四种思路,或者翻译版Largest Rectangle in [email protected],JAVA实现如下:
public int largestRectangleArea(int[] height) { Stack<Integer> stk = new Stack<Integer>(); int ret = 0; for (int i = 0; i <= height.length; i++) { int h=0; if(i<height.length) h=height[i]; if (stk.isEmpty() || h >= height[stk.peek()]) stk.push(i); else { int top = stk.pop(); ret = Math.max(ret, height[top] * (stk.empty() ? i : i - stk.peek() - 1)); i--; } } return ret; }
时间: 2024-12-23 03:41:54