-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaterArea2.java
More file actions
26 lines (25 loc) · 841 Bytes
/
WaterArea2.java
File metadata and controls
26 lines (25 loc) · 841 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
import java.util.*;
class Program {
// O(n) time | O(1) space
public static int waterArea(int[] heights) {
// Write your code here.
if (heights.length == 0) {
return 0;
}
int leftIdx = 0, rightIdx = heights.length - 1;
int leftMax = heights[leftIdx], rightMax = heights[rightIdx];
int totalArea = 0;
while (leftIdx < rightIdx) {
if (heights[leftIdx] < heights[rightIdx]) {
leftIdx++;
leftMax = Math.max(leftMax, heights[leftIdx]);
totalArea += leftMax - heights[leftIdx];
} else {
rightIdx--;
rightMax = Math.max(rightMax, heights[rightIdx]);
totalArea += rightMax - heights[rightIdx];
}
}
return totalArea;
}
}