classSolution{ publicintlargestRectangleArea(int[] heights){ int max=0; int len=heights.length; for(int i =0;i<len;i++){ int num=heights[i]; int start = i; int end = i; while(start>=0 && heights[start]>=num){ start--; } while(end<len && heights[end]>=num){ end++; } int total=num*(end-start-1); max=max>total?max:total; } return max; } }
classSolution{ publicstaticintlargestRectangleArea(int[] heights){ if(heights.length==0){ return0; } int max = 0; Stack<Integer> stack = new Stack(); stack.push(0); int len = heights.length; for (int i = 1; i < len; i++) { int current = heights[i]; int stackTop = heights[stack.peek()]; if (current > stackTop) { stack.push(i); } else { while (!stack.isEmpty() && heights[stack.peek()] >= current) { Integer topIndex = stack.pop(); int start = -1; if (!stack.isEmpty()) { start = stack.peek(); } int area = heights[topIndex] * (i - start - 1); max = max > area ? max : area; } stack.push(i); } } if (!stack.isEmpty()) { Integer top = stack.peek(); while (!stack.isEmpty()) { int height = heights[stack.pop()]; int start = -1; if (!stack.isEmpty()) { start = stack.peek(); } int area = height * (top - start); max = max > area ? max : area; } } return max; } }