mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-12-19 07:00:35 +08:00
* Add Trapping Rainwater problem implementation (Two Pointer Approach) * Add Wikipedia reference link for Trapping Rainwater problem * fix: format TrappingRainwater.java for CI check * fix: add package and resolve checkstyle errors for TrappingRainwater.java * fix: declare TrappingRainwater as final to pass Checkstyle * Add test cases for TrappingRainwater algorithm * Add test cases for TrappingRainwater algorithm * Move TrappingRainwater algorithm to stacks package * Fix: Move TrappingRainwater to stacks and normalize newline in JugglerSequence * Fix: Normalize newline in JugglerSequence to ensure test consistency * Fix: Normalize newline in JugglerSequence and remove return statement * Add JaCoCo plugin for code coverage reporting * Revert pom.xml to original version from master * Fix: Revert the pom.xml file --------- Co-authored-by: Deniz Altunkapan <deniz.altunkapan@outlook.com>
49 lines
1.3 KiB
Java
49 lines
1.3 KiB
Java
package com.thealgorithms.stacks;
|
|
/**
|
|
* Trapping Rainwater Problem
|
|
* Given an array of non-negative integers representing the height of bars,
|
|
* compute how much water it can trap after raining.
|
|
*
|
|
* Example:
|
|
* Input: [4,2,0,3,2,5]
|
|
* Output: 9
|
|
*
|
|
* Time Complexity: O(n)
|
|
* Space Complexity: O(1)
|
|
*
|
|
* Reference: https://en.wikipedia.org/wiki/Trapping_rain_water
|
|
*/
|
|
public final class TrappingRainwater {
|
|
|
|
private TrappingRainwater() {
|
|
throw new UnsupportedOperationException("Utility class");
|
|
}
|
|
|
|
public static int trap(int[] height) {
|
|
int left = 0;
|
|
int right = height.length - 1;
|
|
int leftMax = 0;
|
|
int rightMax = 0;
|
|
int result = 0;
|
|
|
|
while (left < right) {
|
|
if (height[left] < height[right]) {
|
|
if (height[left] >= leftMax) {
|
|
leftMax = height[left];
|
|
} else {
|
|
result += leftMax - height[left];
|
|
}
|
|
left++;
|
|
} else {
|
|
if (height[right] >= rightMax) {
|
|
rightMax = height[right];
|
|
} else {
|
|
result += rightMax - height[right];
|
|
}
|
|
right--;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
}
|