Skip to content

Instantly share code, notes, and snippets.

@Vaib215
Created September 26, 2022 20:41
Show Gist options
  • Save Vaib215/d8731a9253e8c9824075b9c11b4c1c1f to your computer and use it in GitHub Desktop.
Save Vaib215/d8731a9253e8c9824075b9c11b4c1c1f to your computer and use it in GitHub Desktop.
Trapping Rainwater => TC -> O(N)
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