Leetcode Trapping Rain Water (volume of stagnant water)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.