SHARE
TWEET

Untitled

a guest May 21st, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. function trappingRainWater($arr) {
  4.     $n = count($arr);
  5.     $water = 0;
  6.  
  7.     // $left[i] menyimpan nilai maksimum
  8.     // dari array
  9.     $left = [0];
  10.  
  11.     // proses array dari kiri ke kanan
  12.     // dari current bar
  13.     for ($i = 1; $i < $n - 1; $i++) {
  14.         $left[$i] = max($left[$i - 1], $arr[$i - 1]);
  15.     }
  16.  
  17.     // $right menyimpan tinggi max ke kanan
  18.     // dari current bar
  19.     $right = 0;
  20.  
  21.     // process perhitungan dari kanan ke kiri
  22.     for ($i = $n - 2; $i >= 1; $i--) {
  23.         $right = max($right, $arr[$i + 1]);
  24.  
  25.         // cek kemungkinan untuk menampung air pada current bar
  26.         if (min($left[$i], $right) > $arr[$i]) {
  27.             $water += min($left[$i], $right) - $arr[$i];
  28.         }
  29.     }
  30.  
  31.     return $water;
  32. }
  33.  
  34. // Main
  35. $arr = [];
  36. echo implode(',', $arr) . ' = ' . trappingRainWater($arr);
  37. echo "\n";
  38.  
  39. $arr = [0,1,0];
  40. echo implode(',', $arr) . ' = ' . trappingRainWater($arr);
  41. echo "\n";
  42.  
  43. $arr = [2,1,3];
  44. echo implode(',', $arr) . ' = ' . trappingRainWater($arr);
  45. echo "\n";
  46.  
  47. $arr = [0,1,0,2,1,0,1,3,2,1,2,1];
  48. echo implode(',', $arr) . ' = ' . trappingRainWater($arr);
  49. echo "\n";
  50.  
  51. $arr = [2,1,0,2,1,0,1,3,5,1,3,10];
  52. echo implode(',', $arr) . ' = ' . trappingRainWater($arr);
  53. echo "\n";
  54.  
  55. $arr = [12,1,0,2,1,0,1,3,5,1,3,10];
  56. echo implode(',', $arr) . ' = ' . trappingRainWater($arr);
  57. echo "\n";
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top