You have an array of integers, for example: [ 9 8 7 6 2 ].
def rain(l=[]):
result, leftmaxSoFar, rightmaxSoFar = 0, 0, 0
leftMaxList = [0 for i in range(len(l))]
rightMaxList = [0 for i in range(len(l))]
capacity = [0 for i in range(len(l))]
for i in range(len(l)):
leftMaxList[i] = leftmaxSoFar
rightMaxList[len(l) -1 -i] = rightmaxSoFar
if l[i] > leftmaxSoFar :
leftmaxSoFar = l[i]
if l[len(l) -1 -i] > rightmaxSoFar:
rightmaxSoFar = l[len(l) -1 -i]
for i in range(len(l)):
capacity[i] = min(leftMaxList[i], rightMaxList[i]) -l[i]
result = result if capacity[i] < 0 else result+capacity[i]
return result
print rain([3, 1, 3])
print rain( [ 9, 8, 7, 6, 2 ])
You graph the values of the array on the y-axis and the index on the x-axis as a bar graph.
Rain falls on the graph. The water collects in any valleys in the graph, and falls off any edges.
In the example array above no water collects because it all falls to the left and right. In [ 3 1 3 ] We get 2 units of water since it collects in the valley between the two 3 bars.
Devise an algorithm to determine how much water is collected by an array.
Input: Array of integers
Output: Water collected when rain falls on graph
def rain(l=[]):
result, leftmaxSoFar, rightmaxSoFar = 0, 0, 0
leftMaxList = [0 for i in range(len(l))]
rightMaxList = [0 for i in range(len(l))]
capacity = [0 for i in range(len(l))]
for i in range(len(l)):
leftMaxList[i] = leftmaxSoFar
rightMaxList[len(l) -1 -i] = rightmaxSoFar
if l[i] > leftmaxSoFar :
leftmaxSoFar = l[i]
if l[len(l) -1 -i] > rightmaxSoFar:
rightmaxSoFar = l[len(l) -1 -i]
for i in range(len(l)):
capacity[i] = min(leftMaxList[i], rightMaxList[i]) -l[i]
result = result if capacity[i] < 0 else result+capacity[i]
return result
print rain([3, 1, 3])
print rain( [ 9, 8, 7, 6, 2 ])
No comments:
Post a Comment