Untitled
unknown
plain_text
a year ago
861 B
11
Indexable
class Solution {
public int trap(int[] height) {
// base case
int n = height.length;
if (n < 3) return 0;
int trappedWater = 0;
// finding the highest point in the whole map
int highest = 0;
for (int i = 0; i < n; i++) {
if (height[i] > height[highest]) highest = i;
}
// traverse up to the highest point
int left = height[0];
for (int i = 1; i < highest; i++) {
left = Math.max(le
left = Math.max(left, height[i]);
trappedWater += left - height[i];
}
// traverse after the highest point
int right = height[n - 1];
for (int i = n - 2; i > highest; i--) {
right = Math.max(right, height[i]);
trappedWater += right - height[i];
}
return trappedWater;
}
}Editor is loading...
Leave a Comment