Skip to content

Commit 5ebdf46

Browse files
authored
Trapping Rain water in Java
1 parent 9c81ec7 commit 5ebdf46

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Tapping Rain Water

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Test
2+
{
3+
static int arr[] = new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; //Example
4+
5+
static int findWater(int n)
6+
{
7+
int left[] = new int[n];
8+
int right[] = new int[n];
9+
10+
int water = 0;
11+
left[0] = arr[0];
12+
for (int i = 1; i < n; i++)
13+
left[i] = Math.max(left[i-1], arr[i]);
14+
right[n-1] = arr[n-1];
15+
for (int i = n-2; i >= 0; i--)
16+
right[i] = Math.max(right[i+1], arr[i]);
17+
for (int i = 0; i < n; i++)
18+
water += Math.min(left[i],right[i]) - arr[i];
19+
20+
return water;
21+
}
22+

0 commit comments

Comments
 (0)