
Sponsored
Sponsored
This approach involves creating two auxiliary arrays to store the maximum heights on the left and right of each bar. With these arrays, you can calculate how much water each bar can trap.
The water trapped above a bar is determined by the minimum of the maximum heights on its left and right, minus the bar's height itself.
Time Complexity: O(n) because we traverse the height array three times where n is the length of the array.
Space Complexity: O(n) due to the additional arrays used to store the maximum heights.
public int Trap(int[] height) {
if (height == null || height.Length == 0) return 0;
int n = height.Length;
int[] leftMax = new int[n];
int[] rightMax = new int[n];
int water = 0;
leftMax[0] = height[0];
for (int i = 1; i < n; i++) {
leftMax[i] = Math.Max(height[i], leftMax[i - 1]);
}
rightMax[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--) {
rightMax[i] = Math.Max(height[i], rightMax[i + 1]);
}
for (int i = 0; i < n; i++) {
water += Math.Min(leftMax[i], rightMax[i]) - height[i];
}
return water;
}
public static void Main(string[] args) {
int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
Solution solution = new Solution();
Console.WriteLine("Water trapped: " + solution.Trap(height));
}
}
In C#, this solution follows the same logic as others: calculate left and right max heights arrays and subsequently compute the trapped water. The approach uses the same logic framework.
The two-pointer technique optimizes space by keeping track of the left and right bars with two pointers. It uses a single loop and calculates water based on the shorter of the two heights at the current pointers.
Time Complexity: O(n), where n is the length of the input array since we process each bar only once.
Space Complexity: O(1) because we use only constant extra space.
1def trap(height):
2 left, right = 0, len(height) - 1
3 left_max = right_max = 0
4 water = 0
5
6 while left < right:
7 if height[left] < height[right]:
8 if height[left] >= left_max:
9 left_max = height[left]
10 else:
11 water += left_max - height[left]
12 left += 1
13 else:
14 if height[right] >= right_max:
15 right_max = height[right]
16 else:
17 water += right_max - height[right]
18 right -= 1
19
20 return water
21
22height = [0,1,0,2,1,0,1,3,2,1,2,1]
23print(f"Water trapped: {trap(height)}")
24Implementing a two-pointer approach, this Python code starts pointers at each end of the list. Comparing left and right values, it iterates inward to update max heights and compute trapped rainwater efficiently.