[Leetcode]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, computehow much wat Er it is able-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.

Code
/*Trapping Train Water v2*/    intTrap (vector<int> &height) {        intresult=0; intn =height.size (); int*left_flag =New int[n]; int*right_flag =New  int[n]; memset (Left_flag, Int_max, n*sizeof(int)); memset (Right_flag, Int_max, n*sizeof(int)); left_flag[0] =0; Right_flag[n-1] =0; //Scan left         for(inti =1; I < n; i++)        {            if(Height[i-1]>left_flag[i-1]) {Left_flag[i]= Height[i-1]; }            Else{Left_flag[i]= Left_flag[i-1]; }        }        //Scan Right         for(inti = n-2; I >=0; i--)        {            if(Height[i +1] > Right_flag[i +1]) Right_flag[i]= Height[i +1]; ElseRight_flag[i]= Right_flag[i +1]; }         for(size_t i =0; I < n; i++)        {            intCompare = Min (Left_flag[i], right_flag[i])-Height[i]; Result+ = (compare>0? Compare:0); }        Delete[] left_flag; Delete[] right_flag; returnresult; }

Related topics: (M) Container with the most water

Product of Array Except self

[Leetcode]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.