-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaterArea.java
More file actions
34 lines (33 loc) · 862 Bytes
/
WaterArea.java
File metadata and controls
34 lines (33 loc) · 862 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
30
31
32
33
34
import java.util.*;
class Program {
// O(n) time | O(n) space
public static int waterArea(int[] heights) {
// Write your code here.
if (heights.length == 0) {
return 0;
}
int[] containerHeights = new int[heights.length];
int leftMax = 0;
for (int i = 0; i < heights.length; i++) {
int height = heights[i];
containerHeights[i] = leftMax;
leftMax = Math.max(leftMax, height);
}
int rightMax = 0;
for (int i = heights.length - 1; i >= 0; i--) {
int height = heights[i];
int minHeight = Math.min(rightMax, containerHeights[i]);
if (height < minHeight) {
containerHeights[i] = minHeight - height;
} else {
containerHeights[i] = 0;
}
rightMax = Math.max(rightMax, height);
}
int totalArea = 0;
for (int i = 0; i < heights.length; i++) {
totalArea += containerHeights[i];
}
return totalArea;
}
}