Skip to content
Merged
Prev Previous commit
Next Next commit
Update 42 trapping rain water with O(1) space
  • Loading branch information
miladra committed Jul 11, 2022
commit da25527eedda5af6f47f4bf596f9e47a10268272
27 changes: 27 additions & 0 deletions java/42-Trapping-Rain-Water.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,30 @@ public int trap(int[] heights) {
}

}

//O(1) space
class Solution {
public int trap(int[] heights) {

if (heights.length == 0) return 0;

int l = 0, r = heights.length - 1;
int leftMax = heights[l], rightMax = heights[r];
int res = 0;

while (l < r) {
if (leftMax < rightMax) {
l++;
leftMax = Math.max(leftMax, heights[l]);
res += leftMax - heights[l];
} else {
r--;
rightMax = Math.max(rightMax, heights[r]);
res += rightMax - heights[r];
}
}

return res;

}
}