LINK TO CHAT:
https://g.co/gemini/share/320262b94bda
import java.util.Stack;
class Main {
public static int trappingRainStack(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<>();
int ans = 0;
int n = height.length;
// Main loop to iterate through each bar
for (int i = 0; i < n; i++) {
// 1. Finding a container: This loop runs when the current bar is a "right wall"
while (!stack.isEmpty() && height[stack.peek()] < height[i]) {
// 2. Identifying parts of the container
// i. The popped bar is the bottom of the container.
int topIndex = stack.pop();
int pop_height = height[topIndex];
// If stack is empty, there is no left wall, so break.
if (stack.isEmpty()) {
break;
}
// iii. The new top of the stack is the left wall.
int left_wall_index = stack.peek();
// ii. The current bar 'i' is the right wall.
// 3. Calculating the Trapped Water 💧
int width = i - left_wall_index - 1;
int min_height = Math.min(height[left_wall_index], height[i]) - pop_height;
ans += width * min_height;
}
// Push the current bar's index. It might be a future left wall.
stack.push(i);
}
return ans;
}
public static void main(String[] args) {
int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int result = trappingRainStack(arr);
System.out.println("The total trapped water is: " + result); // Output: 6
}
}
No comments:
Post a Comment