Skip to content

Commit 3b37624

Browse files
committed
Add solution of TrappingRainWater task
1 parent 5d48440 commit 3b37624

2 files changed

Lines changed: 74 additions & 0 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package by.andd3dfx.common;
2+
3+
/**
4+
* <pre>
5+
* <a href="https://leetcode.com/problems/trapping-rain-water/description/">Task description</a>
6+
*
7+
* Given n non-negative integers representing an elevation map where the width of each bar is 1,
8+
* compute how much water it can trap after raining.
9+
*
10+
* Example 1:
11+
* <img src="https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" />
12+
*
13+
* Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
14+
* Output: 6
15+
* Explanation: The above elevation map (black section) is represented
16+
* by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
17+
*
18+
* Example 2:
19+
* Input: height = [4,2,0,3,2,5]
20+
* Output: 9
21+
* </pre>
22+
*/
23+
public class TrappingRainWater {
24+
25+
public static int trap(int[] height) {
26+
if (height == null || height.length == 0) {
27+
return 0;
28+
}
29+
30+
int n = height.length;
31+
int[] leftMax = new int[n];
32+
int[] rightMax = new int[n];
33+
int water = 0;
34+
35+
// Calculate left_max
36+
leftMax[0] = height[0];
37+
for (int i = 1; i < n; i++) {
38+
leftMax[i] = Math.max(height[i], leftMax[i - 1]);
39+
}
40+
41+
// Calculate right_max
42+
rightMax[n - 1] = height[n - 1];
43+
for (int i = n - 2; i >= 0; i--) {
44+
rightMax[i] = Math.max(height[i], rightMax[i + 1]);
45+
}
46+
47+
// Calculate trapped water
48+
for (int i = 0; i < n; i++) {
49+
water += Math.min(leftMax[i], rightMax[i]) - height[i];
50+
}
51+
52+
return water;
53+
}
54+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package by.andd3dfx.common;
2+
3+
import static by.andd3dfx.common.TrappingRainWater.trap;
4+
import static org.assertj.core.api.Assertions.assertThat;
5+
6+
import org.junit.Test;
7+
8+
public class TrappingRainWaterTest {
9+
10+
@Test
11+
public void testTrap() {
12+
assertThat(trap(new int[]{1, 0, 1})).isEqualTo(1);
13+
assertThat(trap(new int[]{1, 0, 2})).isEqualTo(1);
14+
assertThat(trap(new int[]{3, 0, 2})).isEqualTo(2);
15+
assertThat(trap(new int[]{1, 3, 1, 2, 0, 1})).isEqualTo(2);
16+
17+
assertThat(trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1})).isEqualTo(6);
18+
assertThat(trap(new int[]{4, 2, 0, 3, 2, 5})).isEqualTo(9);
19+
}
20+
}

0 commit comments

Comments
 (0)