forked from DhanushNehru/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrapping_water.java
More file actions
29 lines (25 loc) · 873 Bytes
/
Trapping_water.java
File metadata and controls
29 lines (25 loc) · 873 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Trapping_water {
public static int trappedRainwater(int height[]){
int n = height.length;
int leftMax[] = new int[n];
leftMax[0] = height[0];
for(int i=1; i<n; i++){
leftMax[i] = Math.max(height[i], leftMax[i-1]);
}
int rightMax[] = new int[n];
rightMax[n-1] = height[n-1];
for(int i=n-2; i>=0; i--){
rightMax[i] = Math.max(height[i], rightMax[i+1]);
}
int trappedWater = 0;
for(int i=0; i<n; i++){
int waterlevel = M
385F
ath.min(leftMax[i], rightMax[i]);
trappedWater += waterlevel - height[i];
}
return trappedWater;
}
public static void main(String[] args){
int height[] = {4, 2, 0, 6, 3, 2, 5};
System.out.println(trappedRainwater(height));
}
}