java: add «42. Trapping Rain Water»

URL:	https://leetcode.com/problems/trapping-rain-water/
This commit is contained in:
Matej Focko 2025-01-09 20:48:09 +01:00
parent b12e923384
commit 9608f3259b
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,20 @@
class Solution {
public int trap(int[] height) {
var caught = 0;
int i = 0, j = height.length - 1;
int maxLeft = height[i], maxRight = height[j];
while (i < j) {
maxLeft = Math.max(maxLeft, height[i]);
maxRight = Math.max(maxRight, height[j]);
if (maxLeft < maxRight) {
caught += maxLeft - height[i++];
} else {
caught += maxRight - height[j--];
}
}
return caught;
}
}