思路很简单,遍历,向左向右找到比当前heights[i]低的柱,下标为left和right,然后底(right - left - 1) * 高(heights[i])
1 2 3 4 5 6 7 8 9 10 11 12
publicintlargestRectangleArea(int[] heights){ if (heights == null || heights.length == 0) return0; int max = Integer.MIN_VALUE; for (int i = 0; i < heights.length; i++) { //往左找,往右找 int left = i, right = i; while (left >= 0 && heights[left] >= heights[i]) left--; while (right < heights.length && heights[right] >= heights[i]) right++; max = Math.max(max, heights[i] * (right - left - 1)); } return max; }
@Test publicvoidtest(){ int[] heights = {2, 1, 5, 6, 2, 3}; int res = largestRectangleArea(heights); System.out.println(res); }
publicintlargestRectangleArea(int[] heights){ int len = heights.length; if (len == 0) return0; if (len == 1) return heights[0];
int res = 0; int[] newHeights = newint[len + 2]; newHeights[0] = 0; System.arraycopy(heights, 0, newHeights, 1, len); newHeights[len + 1] = 0; len += 2; heights = newHeights;
Deque<Integer> stack = new ArrayDeque<>(len); // 先放入哨兵,在循环里就不用做非空判断 stack.addLast(0);
for (int i = 1; i < len; i++) { while (heights[i] < heights[stack.peekLast()]) { int curHeight = heights[stack.pollLast()]; int curWidth = i - stack.peekLast() - 1; res = Math.max(res, curHeight * curWidth); } stack.addLast(i); } return res; } }