|
| 1 | +/**************************************** |
| 2 | +* Problem: Trapping Rain Water |
| 3 | +* |
| 4 | +* Description: |
| 5 | +* Calculates the total amount of rainwater that can be trapped |
| 6 | +* between bars of varying heights after raining. The algorithm |
| 7 | +* uses a two-pointer approach that efficiently computes trapped |
| 8 | +* water by maintaining the maximum heights seen from both ends |
| 9 | +* and moving inward. |
| 10 | +* |
| 11 | +* Approach: |
| 12 | +* - Initialize two pointers (left and right) at both ends. |
| 13 | +* - Track the maximum height on the left and right sides. |
| 14 | +* - Move the pointer with the smaller height inward. |
| 15 | +* - At each step, calculate trapped water based on the difference |
| 16 | +* between the current height and the maximum height on that side. |
| 17 | +* |
| 18 | +* Time Complexity: O(n) - single traversal using two pointers |
| 19 | +* Space Complexity: O(1) - constant extra space |
| 20 | +
|
| 21 | +* Sample Output: |
| 22 | +* Trapped Rainwater: 6 |
| 23 | +* |
| 24 | +* Explanation: |
| 25 | +* Bars at positions 2, 4, 5, 6, 9, and 10 trap water. |
| 26 | +* The total trapped water is 6 units. |
| 27 | +****************************************/ |
| 28 | + |
| 29 | +#include <bits/stdc++.h> |
| 30 | +using namespace std; |
| 31 | + |
| 32 | +// Function to calculate total trapped rainwater |
| 33 | +int calculateTrappedWater(vector<int>& heights) { |
| 34 | + int n = heights.size(); |
| 35 | + int leftIndex = 0, rightIndex = n - 1; |
| 36 | + int totalWater = 0; // Variable to store total trapped water |
| 37 | + int leftMax = 0, rightMax = 0; // Variables to store maximum height encountered from left and right sides |
| 38 | + |
| 39 | + while (leftIndex <= rightIndex) { |
| 40 | + |
| 41 | + // Compare the current heights to decide which pointer to move |
| 42 | + if (heights[leftIndex] <= heights[rightIndex]) { |
| 43 | + if (heights[leftIndex] >= leftMax) |
| 44 | + leftMax = heights[leftIndex]; |
| 45 | + else |
| 46 | + totalWater += leftMax - heights[leftIndex]; |
| 47 | + |
| 48 | + leftIndex++; |
| 49 | + } else { |
| 50 | + if (heights[rightIndex] >= rightMax) |
| 51 | + rightMax = heights[rightIndex]; |
| 52 | + else |
| 53 | + totalWater += rightMax - heights[rightIndex]; |
| 54 | + |
| 55 | + rightIndex--; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return totalWater; |
| 60 | +} |
| 61 | + |
| 62 | +int main() { |
| 63 | + vector<int> elevationMap = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; |
| 64 | + |
| 65 | + cout << "Trapped Rainwater: " << calculateTrappedWater(elevationMap) << endl; |
| 66 | + |
| 67 | + return 0; |
| 68 | +} |
0 commit comments