Skip to content

Commit 69d64e6

Browse files
committed
Added solution for Trapping Rain water problem in java
1 parent 01ba952 commit 69d64e6

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Trapping Rain Water.java

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Java program to find maximum amount of water that can
2+
// be trapped within given set of bars.
3+
4+
class Test
5+
{
6+
static int arr[] = new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
7+
8+
// Method for maximum amount of water
9+
static int findWater(int n)
10+
{
11+
// left[i] contains height of tallest bar to the
12+
// left of i'th bar including itself
13+
int left[] = new int[n];
14+
15+
// Right [i] contains height of tallest bar to
16+
// the right of ith bar including itself
17+
int right[] = new int[n];
18+
19+
// Initialize result
20+
int water = 0;
21+
22+
// Fill left array
23+
left[0] = arr[0];
24+
for (int i = 1; i < n; i++)
25+
left[i] = Math.max(left[i-1], arr[i]);
26+
27+
// Fill right array
28+
right[n-1] = arr[n-1];
29+
for (int i = n-2; i >= 0; i--)
30+
right[i] = Math.max(right[i+1], arr[i]);
31+
32+
// Calculate the accumulated water element by element
33+
// consider the amount of water on i'th bar, the
34+
// amount of water accumulated on this particular
35+
// bar will be equal to min(left[i], right[i]) - arr[i] .
36+
for (int i = 0; i < n; i++)
37+
water += Math.min(left[i],right[i]) - arr[i];
38+
39+
return water;
40+
}
41+
42+
// Driver method to test the above function
43+
public static void main(String[] args)
44+
{
45+
46+
System.out.println("Maximum water that can be accumulated is " +
47+
findWater(arr.length));
48+
}
49+
}

0 commit comments

Comments
 (0)