单调栈及应用示例

单调栈顾名思义就是栈中元素具有单调性,通过举例 [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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值