給定一個數組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;
}