Skip to content

Commit 6bb47fb

Browse files
authored
Merge pull request #108 from dsrao711/issue_107
Python solution for trapping rain water in DSA 450
2 parents 153b2bc + e246e0c commit 6bb47fb

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

DSA 450 GFG/TrapRainWater.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Problem : https://practice.geeksforgeeks.org/problems/trapping-rain-water-1587115621/1
2+
3+
class Solution:
4+
def trappingWater(self, arr,n):
5+
#Code here
6+
left = [0]*n
7+
right = [0]*n
8+
9+
left[0] = arr[0]
10+
right[n-1] = arr[n-1]
11+
trap_sum = 0
12+
13+
for i in range (1 , n):
14+
left[i] = max(left[i-1] , arr[i])
15+
for i in range(n-2 , -1 , -1):
16+
right[i] = max(arr[i] , right[i+1])
17+
for i in range (0 , n):
18+
trap_sum += min(left[i] , right[i]) - arr[i]
19+
20+
return trap_sum
21+
#{
22+
# Driver Code Starts
23+
#Initial Template for Python 3
24+
25+
import math
26+
27+
28+
29+
def main():
30+
T=int(input())
31+
while(T>0):
32+
33+
n=int(input())
34+
35+
arr=[int(x) for x in input().strip().split()]
36+
obj = Solution()
37+
print(obj.trappingWater(arr,n))
38+
39+
40+
T-=1
41+
42+
43+
if __name__ == "__main__":
44+
main()
45+
46+
47+
48+
# } Driver Code Ends

0 commit comments

Comments
 (0)