Advertisement
uopspop

Untitled

Jun 18th, 2021
902
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. class Solution {
  2.     public int trap(int[] height) {
  3.         if (height.length == 0) return 0;
  4.        
  5.         // calculate each pillar indivisually
  6.         int[] left_h_max = new int[height.length];
  7.         int[] right_h_max = new int[height.length];
  8.        
  9.         left_h_max[0] = height[0];
  10.         for (int i = 1; i < height.length ;i++) {
  11.             // attention: i-1 is for left_h_max while i is for height as new incoming number
  12.             left_h_max[i] = Math.max(left_h_max[i-1], height[i]);
  13.         }
  14.        
  15.         right_h_max[height.length - 1] = height[height.length - 1];
  16.         for (int i = height.length - 2; i >= 0 ;i--) {
  17.             // attention: i+1 is for right_h_max while i is for height as new incoming number
  18.             right_h_max[i] = Math.max(right_h_max[i+1], height[i]);
  19.         }
  20.        
  21.         int result = 0;
  22.         for (int i = 0; i < height.length ;i++) {
  23.            
  24.             result += Math.min(left_h_max[i], right_h_max[i]) - height[i];
  25.            
  26.         }
  27.        
  28.         return result;
  29.        
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement