分治算法:
通過觀察,可以發現,最大面積矩形存在於以下幾種情況:
確定了最矮柱子以后,矩形的寬盡可能往兩邊延伸。
在最矮柱子左邊的最大面積矩形(子問題)。
在最矮柱子右邊的最大面積矩形(子問題)。
舉個例子:
[6, 4, 5, 2, 4, 3, 9]
[6, 4, 5, 2, 4, 3, 9]
這里最矮柱子高度為 2 。以 2 為高的最大子矩陣面積是 2x7=14 。現在,我們考慮上面提到的第二種和第三種情況。我們對高度為 2 柱子的左邊和右邊采用同樣的過程。在 2 的左邊, 4 是最小的,形成區域為 4x3=12 。將左邊區域再繼續分,矩形的面積分別為 6x1=6 和 5x1=5 。同樣的,我們可以求出右邊區域的面積為 3x3=9, 4x1=4 和 9x1=9 。因此,我們得到最大面積是 16 。具體過程可參考下圖:

代碼:
public class Solution { public int calculateArea(int[] heights, int start, int end) { if (start > end) return 0; int minindex = start; for (int i = start; i <= end; i++) if (heights[minindex] > heights[i]) minindex = i; return Math.max(heights[minindex] * (end - start + 1), Math.max(calculateArea(heights, start, minindex - 1), calculateArea(heights, minindex + 1, end))); } public int largestRectangleArea(int[] heights) { return calculateArea(heights, 0, heights.length - 1); } }