给定一个数组a,数组的每个成员代表x轴上每个区域宽度为1的一个台阶高度,计算下雨时,这个台阶最多能够积多少(面积)雨水?
public function water($heights)
{
$hc = count($heights);
if( $hc<= 2)
{
return 0;
}
//获取最高点
$heightMax = $heights[0];
for($i=0;$i<$hc;$i++)
{
if($heights[$i] > $heightMax){
$heightMax = $heights[$i];
$maxIndex = $i;
}
}
//计算面积
$area = 0;
$left = $heights[0];
//左侧至最高点
for($i = 0;$i < $maxIndex;$i++){
if($left<$heights[$i]){
$left = $heights[$i];
}else{
$area += ($left - $heights[$i]);
}
}
//右侧至最高点
for($i = $hc-1,$right = $heights[$hc-1];$i>$maxIndex;$i--){
if($right<$heights[$i]){
$right = $heights[$i];
}else{
$area += ($right - $heights[$i]);
}
}
return $area;
}