Trapping Rain Water

Source: Internet
Author: User

Describe
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute
How much water it was able to the trap after raining.
For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6

Analysis
For each pillar, find the tallest pillar on the left and right side, the area that the pillar can hold is min (Max_left,
Max_right)-height. So

1. Scan from left to right, and for each pillar, the left maximum value is obtained;
2. Scan from right to left, for each column, the maximum right value;
3. Scan again and add up the area of each pillar.
can also,
1. Scan once and find the highest pillar, which divides the array into two halves;
2. Handle the left half;
3. Handle the right half.
Code

1  Packagestacksandqueues;2 3  Public classTrappingrainwater {4 5      Public Static voidMain (string[] args) {6         //TODO auto-generated Method Stub7         //from left to right to find the largest, and then from right to left to find the largest, currently the largest-currently array[i]; find the smallest of them, that is, the amount of water stored. 8     int[] array= {0,1,0,2,1,0,1,3,2,1,2,1};9 System.out.println (Trap (array));Ten     } One  A      Public Static intTrapint[] Array) { -         if(Array.Length = = 0) -             return0; the         intLen = array.length-1; -         int[] Maxl =New int[Len + 1]; -         int[] MaxR =New int[Len + 1]; -         intCap = 0, total = 0; +          for(inti = len; I >= 0; i--) { -Maxr[i] =cap; +             if(Array[i] >cap) ACap =Array[i]; at         } -Cap = 0; -          for(inti = 0; I <= Len; i++) { -Maxl[i] =cap; -             if(Array[i] >cap) -Cap =Array[i]; in         } -          for(inti = 0; I <= Len; i++) { to             intc = Math.min (Maxl[i], maxr[i])-Array[i]; +             if(C > 0) -Total + =C; the         } *         returnTotal ; $     }Panax Notoginseng}

Trapping Rain 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.