Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int trap(int[] height) {
- if (height.length == 0) return 0;
- // calculate each pillar indivisually
- int[] left_h_max = new int[height.length];
- int[] right_h_max = new int[height.length];
- left_h_max[0] = height[0];
- for (int i = 1; i < height.length ;i++) {
- // attention: i-1 is for left_h_max while i is for height as new incoming number
- left_h_max[i] = Math.max(left_h_max[i-1], height[i]);
- }
- right_h_max[height.length - 1] = height[height.length - 1];
- for (int i = height.length - 2; i >= 0 ;i--) {
- // attention: i+1 is for right_h_max while i is for height as new incoming number
- right_h_max[i] = Math.max(right_h_max[i+1], height[i]);
- }
- int result = 0;
- for (int i = 0; i < height.length ;i++) {
- result += Math.min(left_h_max[i], right_h_max[i]) - height[i];
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement