[Leetcode] (python): 042-trapping Rain Water

Source: Internet
Author: User

Source of the topic

https://leetcode.com/problems/trapping-rain-water/

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 .


Test instructions Analysis

Input:the height of the bars as list

Output:the volumn of the water the bars can save

Conditions: Notice that the bar height is different, so the middle bar can hold a certain amount of water, test instructions is the size of the water to be accommodated

Topic ideas

Note that the amount of water that each bar can hold is the lower value of the bar in its left and right bar, so first create a leftmosthigh list to record the highest bar value before each bar and then traverse backward from the back to the top bar value Calculate the amount of water that each bar can hold at a time

AC Code (PYTHON)

1_author_ ="YE"2 #-*-coding:utf-8-*-3 4 classsolution (object):5     defTrap (self, height):6         """7 : Type Height:list[int]8 : Rtype:int9         """TenL =len (height) OneLeftmosthigh = [0 forIinchRange (len (height))] ALeftmax =0 -          forIinchRange (L): -Leftmosthigh[i] =Leftmax the             ifHeight[i] >Leftmax: -Leftmax =Height[i] -  -Rightmax =0 +sum =0 -          forIinchReversed (Range (L)): +             ifMin (Rightmax, leftmosthigh[i]) >Height[i]: Asum = sum + min (Rightmax, leftmosthigh[i])-Height[i] at             ifHeight[i] >Rightmax: -Rightmax =Height[i] -  -         returnsum -  -  inHeight = [0,1,0,2,1,0,1,3,2,1,2,1] -s =solution () to Print(S.trap (height))

[Leetcode] (python): 042-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.