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!
idea: This problem and https://oj.leetcode.com/problems/candy/a bit like, respectively using Leftmax[a.length] and rightmax[A.length] To store A[i] to the left of the maximum and a[i] to the right of the maximum value. when A[i]<math.min (Leftmax[i], rightmax[i]), then the position I can store water, otherwise it cannot store water.
public class Solution {public int trap (int[] A) {int result = 0,temp;int []leftmax=new int [A.length];int] []rightmax=new i NT [a.length];for (int i=0,max=-1;i<a.length;i++) {leftmax[i]=max;max=max>a[i]? Max:a[i];} for (int i=a.length-1,max=-1;0<=i;i--) {rightmax[i]=max;max=max>a[i]? Max:a[i];} for (int i=1;i<a.length-1;i++) {temp=math.min (Leftmax[i], rightmax[i]), if (Temp>a[i]) {result+=temp-a[i];}} return result;}}
Leetcode trapping Rain Water