Advertisement
Iam_Sandeep

42. Trapping Rain Water

Jul 31st, 2022
1,005
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. class Solution:
  2.     def trap(self, a: List[int]) -> int:
  3.         n=len(a)
  4.         l,r=0,n-1
  5.         lmax,rmax=0,0
  6.         ans=0
  7.         while l<r:
  8.             '''
  9.            Why dont we need rmax .2 cases here
  10.            1)Because lets say there is a bar greater than a[l] in between l,n-1
  11.            then lmax should be min(lmax,rmax)
  12.            2)Lets say tere is no bar greater than a[l] in bertween l and n-1,the obviously a[r] will be max as we moved to
  13.            l in while block. See code for more understanding.
  14.            '''
  15.             if a[l]<a[r]:
  16.                 lmax=max(lmax,a[l])
  17.                 ans+=lmax-a[l]
  18.                 l+=1
  19.            
  20.             else:
  21.                 rmax=max(rmax,a[r])
  22.                 ans+=rmax-a[r]
  23.                 r-=1
  24.         return ans
  25. class Solution:
  26.     def trap(self, a: List[int]) -> int:
  27.        
  28.         n=len(a)
  29.         left,right=[0]*n,[0]*n
  30.         left[0]=a[0]
  31.         right[-1]=a[-1]
  32.         for i in range(1,n):
  33.             left[i]=max(a[i],left[i-1])
  34.        
  35.         for i in range(n-2,-1,-1):
  36.             right[i]=max(right[i+1],a[i])
  37.         ans=0
  38.         for i in range(n):
  39.             ans+=(min(left[i],right[i])-a[i])
  40.         return ans
  41.  
  42. #trapping rain water 2
  43. import heapq as hq
  44. class Solution:
  45.     def trapRainWater(self, h: List[List[int]]) -> int:
  46.         q=[]
  47.         m,n=len(h),len(h[0])
  48.         vis=[[False]*n for i in range(m)]
  49.      
  50.         for i in range(m):
  51.             for j in range(n):
  52.                 if i==0 or j==0 or i==m-1 or j==n-1:
  53.                     q.append((h[i][j],i,j))
  54.                     vis[i][j]=True
  55.                    
  56.         hq.heapify(q)
  57.         ans=0
  58.         while q:
  59.             t,i,j=hq.heappop(q)
  60.             for u,v in (0,1),(1,0),(0,-1),(-1,0):
  61.                 x,y=i+u,j+v
  62.                 if 0<=x<m and 0<=y<n and vis[x][y]==False:
  63.                     if h[x][y]>=t:
  64.                         hq.heappush(q,(h[x][y],x,y))
  65.                     else:
  66.                         ans+=(t-h[x][y])
  67.                         hq.heappush(q,(t,x,y))
  68.                     vis[x][y]=True
  69.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement