Trapping Rain Water

Source: Internet
Author: User

Https://leetcode.com/problems/trapping-rain-water/#/solutions

Here's my idea:instead of calculating area by Height*width, we can think it in a cumulative. In the other words, the sum water amount of each bin (width=1).
Search from left to right and maintain a max height of left and right separately, which was like a one-side wall of partial Container. Fix the higher one and flow water from the lower part. For example, if current height of lower, we fill water in the left bin. Until left meets right, we filled the whole container.

Left and right pointers, maximum maintenance, positive sequence, reverse order

Class Solution {public:    int trap (int a[], int n) {        int left=0; int right=n-1;        int res=0;        int maxleft=0, maxright=0;        while (left<=right) {            if (A[left]<=a[right]) {                if (a[left]>=maxleft) maxleft=a[left];                else Res+=maxleft-a[left];                left++;            }            else{                if (a[right]>=maxright) maxright= a[right];                else Res+=maxright-a[right];                right--;            }        }        return res;    }};

  

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.