title Link: https://leetcode.com/problems/trapping-rain-water/?tab=Description
Problem: According to the value of the given array, follow. To solve the maximum volume of water accumulation. First, the array is traversed, the maximum height of the corresponding subscript is maxindex after the left-to-right traversal, set the left height of Leftmax and initialized to Height[0], from I==1 to I==maxindex to traverse. Constantly updated water, and Leftmax when Height[i] is less than leftmax, water + = Leftmax-height when height[i] is greater than leftmax, Leftmax = Height[i] from I==he Ight.length-2 to subscript I = = Maxindex for traversal operation initialization Rightmax = height[height.length-1]when Height[i] is less than Rightmax, Water+=rightmax-height[i]When Height[i] is greater than rightmax, Rightmax = Height[i]
function results return water Reference Code:
Packageleetcode_50;/*** * * @authorPengfei_zheng * To find the volume of stagnant water*/ Public classSolution42 { Public Static intTrapint[] height) { if(Height.length <= 2)return0; intmax =-1; intMaxindex = 0; for(inti = 0; i < height.length; i++) { if(Height[i] >max) {Max=Height[i]; Maxindex=i; } } intLeftmax = height[0]; intWater = 0; for(inti = 1; i < Maxindex; i++) { if(Height[i] >Leftmax) {Leftmax=Height[i]; } Else{Water+ = Leftmax-Height[i]; } } intRightmax = height[height.length-1]; for(intI= height.length-2; i > Maxindex; i--) { if(Height[i] >Rightmax) {Rightmax=Height[i]; } Else{Water+ = Rightmax-Height[i]; } } returnwater; } Public Static voidMain (String[]args) {//int []height={0,1,0,2,1,0,1,3,2,1,2,1}; int[]height={10,0,11,0,10}; System.out.println (Trap (height)); }}
Leetcode Trapping Rain Water (volume of stagnant water)