Last active
December 28, 2015 02:39
-
-
Save thulka/7429806 to your computer and use it in GitHub Desktop.
Michael Kozakov blogged about a twitter interview question
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# twitter interview question: http://qandwhat.apps.runkite.com/i-failed-a-twitter-interview/ | |
# | |
# single pass | |
# recursive | |
# | |
# for debug and understanding, the function acc(umulate) returns the array of water levels in each bin. | |
def acc(land, i=0, leftmax=0): | |
leftmax = max(leftmax, land[i]) | |
puddles, rightmax = acc(land, i+1, leftmax) if i < len(land)-1 else ([], 0) | |
rightmax = max(rightmax, land[i]) | |
water = min(leftmax, rightmax) - land[i] # compute current water | |
water = max(water, 0) | |
return [water] + puddles, rightmax # water heights, rightmax | |
# usage | |
land = [7,0,5,0,7,0] | |
puddles, _ = acc(land) | |
print(puddles) | |
print(sum(puddles)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment