forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrappingRainwater.java
More file actions
48 lines (45 loc) · 1.26 KB
/
TrappingRainwater.java
File metadata and controls
48 lines (45 loc) · 1.26 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.thealgorithms.stacks;
/**
* Trapping Rainwater Problem
* Given an array of non-negative integers representing the height of bars,
* compute how much water it can trap after raining.
*
* Example:
* Input: [4,2,0,3,2,5]
* Output: 9
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* Reference: https://en.wikipedia.org/wiki/Trapping_rain_water
*/
public final class TrappingRainwater {
private TrappingRainwater() {
throw new UnsupportedOperationException("Utility class");
}
public static int trap(int[] height) {
int left = 0;
int right = height.length - 1;
int leftMax = 0;
int rightMax = 0;
int result = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
result += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
result += rightMax - height[right];
}
right--;
}
}
return result;
}
}