
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.
1public class Solution {
2 public int Trap(int[] height) {
3 if (height == null || height.Length == 0) return 0;
4 int n = height.Length;
5 int[] leftMax = new int[n];
6 int[] rightMax = new int[n];
7 int water = 0;
8
9 leftMax[0] = height[0];
10 for (int i = 1; i < n; i++) {
11 leftMax[i] = Math.Max(height[i], leftMax[i - 1]);
12 }
13
14 rightMax[n - 1] = height[n - 1];
15 for (int i = n - 2; i >= 0; i--) {
16 rightMax[i] = Math.Max(height[i], rightMax[i + 1]);
17 }
18
19 for (int i = 0; i < n; i++) {
20 water += Math.Min(leftMax[i], rightMax[i]) - height[i];
21 }
22
23 return water;
24 }
25
26 public static void Main(string[] args) {
27 int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
28 Solution solution = new Solution();
29 Console.WriteLine("Water trapped: " + solution.Trap(height));
30 }
31}
32In 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.
1#
This approach leverages two pointers, starting from both ends of the array and moving towards the center. It dynamically updates the maximum height seen so far from either direction and calculates water trapped at the current position based on these max heights.