单调栈顾名思义就是栈中元素具有单调性,通过举例 [6,7,5,2,4,5,9,3] 来深入了解。
枚举6时,初始时栈为空,直接入栈,栈:[6(0)]
。(这里括号内的数字表示柱子在原数组中的位置)
枚举 7 时,栈顶元素 6 < 7,不移除栈顶元素,7 入栈,栈:[6(0),7(1)];
枚举 5 时,栈顶元素 7 >= 5,因此移除,接下来栈顶元素 6 >= 5,继续移除,5 入栈,栈[5(2)];
枚举 2 时,栈顶元素 5 >= 2,移除栈顶元素,2 入栈,栈:[2(3)];
接下来枚举 4,5,9 都 >= 2,一一入栈,栈:[2(3),4(4),5(5),9(6)];
最后枚举 3 时,依次移除栈顶元素 9, 5, 4, 3 入栈,栈:[2(3),3(7)]
代码:
$heights = [6,7,5,2,4,5,9,3];
$map = [];
for ($i=0; $i < count($heights); $i++) {
// >=递增 <递减
while (!empty($map) && end($map) >= $heights[$i]) {
array_pop($map);
}
array_push($map,$heights[$i]);
}
题目:
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
/**
* @param Integer[] $heights
* @return Integer
*/
function largestRectangleArea($heights) {
$map = [];
$left = [];
$right = [];
for ($i=0; $i < count($heights); $i++) {
while (!empty($map) && $heights[end($map)] >= $heights[$i]) {
array_pop($map);
}
// 左边界哨兵为 -1
$left[$i] = empty($map) ? -1 : end($map);
array_push($map,$i);
}
$map = [];
for ($i=count($heights)-1; $i >= 0; $i--) {
while (!empty($map) && $heights[end($map)] >= $heights[$i]) {
array_pop($map);
}
// 右边界哨兵为 count($heights)
$right[$i] = empty($map) ? count($heights) : end($map);
array_push($map,$i);
}
$s = 0;
for ($i=0; $i < count($heights); $i++) {
$s = max($s,($right[$i]-$left[$i]-1)*$heights[$i]);
}
return $s;
}