給定 n 個非負整數,用來表示柱狀圖中各個柱子的高度。每個柱子彼此相鄰,且寬度爲 1 。
求在該柱狀圖中,能夠勾勒出來的矩形的最大面積。
以上是柱狀圖的示例,其中每個柱子的寬度爲 1,給定的高度爲 [2,1,5,6,2,3]。
圖中陰影部分爲所能勾勒出的最大矩形面積,其面積爲 10 個單位。
示例:
輸入: [2,1,5,6,2,3]
輸出: 10
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/largest-rectangle-in-histogram
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分治法
問題可分爲三種情況:
1.找出最短柱子,矩形的寬儘可能往兩邊延伸
2.在最短柱子的左邊找出最大面積
3.在最短柱子的右邊找出最大面積
舉例[2,1,5,6,2,3]
最短柱子爲1,寬度爲6,面積1*6=6
對高度爲1的左右兩邊採取同樣的過程
1的左邊,形成面積2*1=2;1的右邊,最短柱子2,形成面積2*4=8,以此類推,2的左邊形成5*2=10,6*1=6,2的右邊3*1=3
最終得到面積最大值5*2=10
class Solution {
public int largestRectangleArea(int[] heights) {
return calculateMaxArea(heights, 0, heights.length - 1);
}
private int calculateMaxArea(int[] heights, int left, int right) {
if (left > right) return 0;
int minIndex = left;
//求出最短柱子
for (int i = left; i <= right; i++) {
if (heights[i] < heights[minIndex]) {
minIndex = i;
}
}
return Math.max(heights[minIndex] * (right - left + 1),
Math.max(calculateMaxArea(heights, left, minIndex - 1), calculateMaxArea(heights, minIndex + 1, right)));
}
}