Question:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
Thought:
Take one element in the array as example, if we want to see how much water this position can trap, we will need to use Math.min(left highest boundary, right highest bundary) – current height. Thus, we need to calculate the left highest boundary for each position and the right highest boundary for each position.
Code:
public int trap(int[] height) { if (height.length < 2) return 0; int len = height.length; int[] left = new int[len]; int[] right = new int[len]; int max = height[0]; for (int i = 0; i < len; i++) { max=Math.max (max, height[i]); left[i] = max; } max = height[len - 1]; for (int i = len - 1; i >= 0; i--) { max=Math.max (max, height[i]); right[i] = max; } int re = 0; for (int i = 0; i < len ; i++) { re += Math.min (left[i], right[i]) - height[i]; } return re; }