<?php

error_reporting(-1);

function getWaterVolume(array $landscape)
{
    $lefts = array();
    $rights = array();
    $water = array();

    $maxLeft = 0;
    $maxRight = 0;

    for ($i = 0; $i < count($landscape); $i++) {
    	$maxLeft = max($maxLeft, $landscape[$i]);
        $lefts[$i] = $maxLeft;
    }

    for ($i = count($landscape) - 1; $i >= 0; $i--) {
        $maxRight = max($maxRight, $landscape[$i]);
        $rights[$i] = $maxRight;
        $water[$i] = min($rights[$i], $lefts[$i]) - $landscape[$i];
    }
    
    return array_sum($water);
}

$inputs = array(
	array(0, 5, 0, 1, 0, 2, 0),
	array(0, 5, 4, 3, 3, 2, 0),
	array(2, 5, 1, 2, 3, 4, 7, 7, 6)
);

foreach ($inputs as $landscape) {
	echo implode(", ", $landscape).' → '.getWaterVolume($landscape)."\n";
}

