#! /usr/bin/env python2.7 # A proposed solution to https://leetcode.com/problems/trapping-rain-water/description/ def last_index(arr): """ For a given array, a map indexed by unique values in the array whose values are the last index of the given value. e.g. [0,3,1,2,3,1] would return {0:0, 3:4, 1:5, 2:4} """ ret = {} for idx, val in enumerate(arr): ret[val] = idx return ret def rain_water(arr): """ Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. """ trapped = 0 actionableMax = 0 lastmax = last_index(arr) for idx, val in enumerate(arr[:-1]): # We use [:-1] because the last slot will never trap water if val > actionableMax: # This may be a new actionableMax **if** it's not the last time we see this value if lastmax[val] > idx: # Nope, not the last time! actionableMax = val elif val < actionableMax: diff = actionableMax - val trapped += diff return trapped print rain_water([0,1,0,2,1,0,1,3,2,1,2,1])
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question