
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.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int trap(std::vector<int>& height) {
6 int n = height.size();
7 if (n == 0) return 0;
8 std::vector<int> leftMax(n), rightMax(n);
9 int water = 0;
10
11 leftMax[0] = height[0];
12 for (int i = 1; i < n; ++i) {
13 leftMax[i] = std::max(height[i], leftMax[i - 1]);
14 }
15
16 rightMax[n - 1] = height[n - 1];
17 for (int i = n - 2; i >= 0; --i) {
18 rightMax[i] = std::max(height[i], rightMax[i + 1]);
19 }
20
21 for (int i = 0; i < n; ++i) {
22 water += std::min(leftMax[i], rightMax[i]) - height[i];
23 }
24
25 return water;
26}
27
28int main() {
29 std::vector<int> height = {0,1,0,2,1,0,1,3,2,1,2,1};
30 std::cout << "Water trapped: " << trap(height) << std::endl;
31 return 0;
32}
33In this C++ implementation, we use two std::vector objects (leftMax and rightMax) to store the maximum height up to each index from the left and right. The water trapped is computed similarly to other languages.
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.
1public class Solution {
public int Trap(int[] height) {
int left = 0, right = height.Length - 1;
int leftMax = 0, rightMax = 0, water = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
water += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
water += rightMax - height[right];
}
right--;
}
}
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 algorithm applies the two-pointer approach by comparing and processing the boundaries inward, ensuring the highest landmarks are utilized for efficient water trapping computations without additional data structure overhead.