Trapping Raining Water Solution

Source: Internet
Author: User

Question

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 .

Solution

Referrence

The Key to the solution was to know, which for each point a[i], and the max is was calculated by:

Min (left,right) –a[i]

Left was the maximum height before a[i], right was the maximum height after a[i].

Therefore, we can create a. Arrays to the record left of most of the height and right of most of the height for each point. Time complexity O (n).

1  Public classSolution {2      Public intTrapint[] height) {3         if(Height = =NULL|| Height.length < 1)4             return0;5         intLength =height.length;6         int[] leftmost =New int[length];7         int[] rightmost =New int[length];8         //First , find left biggest hight9Leftmost[0] = 0;Ten          for(inti = 1; i < length; i++) OneLeftmost[i] = Math.max (leftmost[i-1], height[i-1]); A          -         //Then , find right biggest hight -Rightmost[length-1] = 0; the          for(inti = length-2; I >= 0; i--) -Rightmost[i] = Math.max (rightmost[i + 1], Height[i + 1]); -          -         //Calculate sum +         intresult = 0; -          for(inti = 0; i < length; i++) { +             intTMP = Math.min (Leftmost[i], rightmost[i])-Height[i]; A             if(tmp > 0) atResult + =tmp; -         } -         returnresult; -     } -}

Trapping Raining Water Solution

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.