Created
September 26, 2022 20:41
-
-
Save Vaib215/d8731a9253e8c9824075b9c11b4c1c1f to your computer and use it in GitHub Desktop.
Trapping Rainwater => TC -> O(N)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int trappedRW(int arr[]){ | |
int n=arr.length, leftMB[] = new int[n], rightMB[] = new int[n],trappedWater=0; | |
leftMB[0] = arr[0]; | |
rightMB[n-1] = arr[n-1]; | |
for (int i = 1; i < n; i++) { | |
leftMB[i] = Math.max(leftMB[i-1], arr[i]); | |
} | |
for (int i = n-2; i >= 0; i--) { | |
rightMB[i] = Math.max(rightMB[i+1],arr[i]); | |
} | |
for(int i=0; i<n; i++){ | |
int waterLevel = Math.min(leftMB[i], rightMB[i]); | |
trappedWater += waterLevel - arr[i]; | |
} | |
return trappedWater; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment