Problem:
Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1] , return 6 .
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image! C
Code:
public class Solution {public int trap (int[] a) { if (a = = NULL | | A.length = = 0) { return 0; } int[] leftmost = new Int[a.length]; int[] rightmost = new Int[a.length]; Leftmost[0] = a[0]; RIGHTMOST[A.LENGTH-1] = a[a.length-1]; for (int i = 1; i < a.length; i++) { Leftmost[i] = Math.max (Leftmost[i-1], a[i]); } for (int i = a.length-2; I >= 0; i--) { Rightmost[i] = Math.max (rightmost[i + 1], a[i]); } int sum = 0; for (int i = 1; i < a.length-1; i + +) { sum = sum + (Math.min (Rightmost[i], leftmost[i])-a[i]); } return sum; }}
Leetcode:trapping Rain Water