Skip to content

Commit

Permalink
Update 42 trapping rain water with O(1) space
Browse files Browse the repository at this point in the history
  • Loading branch information
miladra committed Jul 11, 2022
1 parent baf691d commit da25527
Showing 1 changed file with 27 additions and 0 deletions.
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;

}
}

0 comments on commit da25527

Please sign in to comment.