Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Groovy version of the "Calculate Rain Volume" algorithm.
def walls = [ 2, 5, 1, 2, 3, 4, 7, 7, 6 ]
println(calculateVolume(walls))
assert 10 == calculateVolume(walls)
def calculateVolume(land) {
def leftMax = 0
def rightMax = 0
def left = 0
def right = land.size() - 1
def volume = 0
while(left < right) {
if(land[left] > leftMax) {
leftMax = land[left]
}
if(land[right] > rightMax) {
rightMax = land[right]
}
if (leftMax >= rightMax) {
volume += rightMax - land[right]
right--
} else {
volume += leftMax - land[left]
left++
}
}
return volume
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.