fork(1) download
  1. <?php
  2.  
  3.  
  4. function getWaterVolume(array $landscape)
  5. {
  6. $lefts = array();
  7. $rights = array();
  8. $water = array();
  9.  
  10. $maxLeft = 0;
  11. $maxRight = 0;
  12.  
  13. for ($i = 0; $i < count($landscape); $i++) {
  14. $maxLeft = max($maxLeft, $landscape[$i]);
  15. $lefts[$i] = $maxLeft;
  16. }
  17.  
  18. for ($i = count($landscape) - 1; $i >= 0; $i--) {
  19. $maxRight = max($maxRight, $landscape[$i]);
  20. $rights[$i] = $maxRight;
  21. $water[$i] = min($rights[$i], $lefts[$i]) - $landscape[$i];
  22. }
  23.  
  24. return array_sum($water);
  25. }
  26.  
  27. $inputs = array(
  28. array(0, 5, 0, 1, 0, 2, 0),
  29. array(0, 5, 4, 3, 3, 2, 0),
  30. array(2, 5, 1, 2, 3, 4, 7, 7, 6)
  31. );
  32.  
  33. foreach ($inputs as $landscape) {
  34. echo implode(", ", $landscape).' → '.getWaterVolume($landscape)."\n";
  35. }
  36.  
  37.  
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
0, 5, 0, 1, 0, 2, 0 → 5
0, 5, 4, 3, 3, 2, 0 → 0
2, 5, 1, 2, 3, 4, 7, 7, 6 → 10