I came across this interview question to find water accumulated between towers:
You are given an input array whose each element represents the height of the tower. The width of every tower is 1. You pour water from the top. How much water is collected between the towers?
Any suggestions?
def test(x):
if len(x) <= 2 or x == sorted(x) or x == sorted(x, reverse=True):
return 0
area = 0
count = 1
max_height = x[0]
while count < len(x) - 1:
if x[count] < max_height and x[count:] != sorted(x[count:], reverse=True):
temp_count = 0
new_count = count
temp_height = 0
height = max_height
while count < len(x):
if x[count] >= height or count == len(x) - 1:
temp_count = count
temp_height = x[count]
height = min(max_height, temp_height)
break
count += 1
while new_count < temp_count:
area += height - x[new_count]
new_count += 1
else:
max_height = x[count]
count += 1
return area
try:
a = [1,2,3,4,5]
print a, test(a)
b = [5,4,3,9,1]
print b, test(b)
c = [3,2,1,1,1,2,3]
print c, test(c)
e = [1,2,0,2,1]
print e, test(e)
f = [1, 4, 2, 5, 1, 2, 3]
print f, test(f)
g = [3, 2, 1, 1, 1, 2, 3]
print g, test(g)
a1 = [1001,1000,1002]
print a1, test(a1)
except Exception as e:
print e