给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

<?phpclass Solution {public function trap($height) {$stackKey = new SplStack();$volume = 0;for ($i = 0; $i < count($height); $i++) {if ($stackKey->isEmpty() || $height[$i] <= $height[$stackKey->top()]) {$stackKey->push($i);} else {while (!$stackKey->isEmpty() && $height[$i] > $height[$stackKey->top()]) {$top = $stackKey->pop();if (!$stackKey->isEmpty()) {$volume += ($i - $stackKey->top() + 1) * (min($height[$i], $height[$stackKey->top()]) - $height[$top]);}}}}return $volume;}}$height = [0,1,0,2,1,0,1,3,2,1,2,1];$cls = new Solution();$volume = $cls->trap($height);echo $volume;
