Leetcode "trapping Rain water" python implementation

Source: Internet
Author: User

title :

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 .

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!

code : OJ Test via runtime:91 ms

1 classSolution:2     #@param A, a list of integers3     #@return An integer4     defTrap (self, A):5         #Special Case6         ifLen (A) <3:7             return08         #Left most & right most9Length=Len (A)TenLeft_most = [0 forIinchrange (LENGTH)] OneRight_most = [0 forIinchrange (LENGTH)] ACurr_max =0 -          forIinchRange (LENGTH): -             ifA[i] >Curr_max: theCurr_max =A[i] -Left_most[i] =Curr_max -Curr_max =0 -          forIinchRange (length-1,-1,-1): +             ifA[i] >Curr_max: -Curr_max =A[i] +Right_most[i] =Curr_max A         #Sum the trap atsum =0 -          forIinchRange (LENGTH): -sum = sum + MAX (0,min (Left_most[i],right_most[i])-A[i]) -         returnSum

Ideas :

Bottom line: How much water a position can put on, depending on the smallest of the left and right sides with this position position high.

Imagine the physical environment in which a location can hold water, ensuring that the position is in a low-lying position. How can we meet the conditions of the low-lying position? Both sides have to have a higher element than this position. What if we can guarantee that there are more elements on both left and right that are higher than this position? As long as the left and right sides of the maximum value of the smaller one than this position large can be.

Leetcode "trapping Rain water" python implementation

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.