|
| 1 | +/** |
| 2 | + * @file |
| 3 | + * @brief Implementation of the Trapped Rainwater Problem |
| 4 | + * @details |
| 5 | + * This implementation calculates the amount of rainwater that can be trapped |
| 6 | + * between walls represented by an array of heights. |
| 7 | + */ |
| 8 | + |
| 9 | +#include <algorithm> /// For std::min and std::max |
| 10 | +#include <cassert> /// For assert |
| 11 | +#include <iostream> /// For IO operations |
| 12 | +#include <vector> /// For vector container |
| 13 | + |
| 14 | +/* |
| 15 | + * @namespace |
| 16 | + * @brief Dynamic Programming Algorithms |
| 17 | + */ |
| 18 | +namespace dynamic_programming { |
| 19 | +/** |
| 20 | + * @brief Function to calculate the trapped rainwater |
| 21 | + * @param heights Array representing the heights of walls |
| 22 | + * @return The amount of trapped rainwater |
| 23 | + */ |
| 24 | +int trappedRainwater(const std::vector<int>& heights) { |
| 25 | + int n = heights.size(); |
| 26 | + if (n <= 2) |
| 27 | + return 0; // No water can be trapped with less than 3 walls |
| 28 | + |
| 29 | + std::vector<int> leftMax(n), rightMax(n); |
| 30 | + |
| 31 | + // Calculate the maximum height of wall to the left of each wall |
| 32 | + leftMax[0] = heights[0]; |
| 33 | + for (int i = 1; i < n; ++i) { |
| 34 | + leftMax[i] = std::max(leftMax[i - 1], heights[i]); |
| 35 | + } |
| 36 | + |
| 37 | + // Calculate the maximum height of wall to the right of each wall |
| 38 | + rightMax[n - 1] = heights[n - 1]; |
| 39 | + for (int i = n - 2; i >= 0; --i) { |
| 40 | + rightMax[i] = std::max(rightMax[i + 1], heights[i]); |
| 41 | + } |
| 42 | + |
| 43 | + // Calculate the trapped rainwater between walls |
| 44 | + int trappedWater = 0; |
| 45 | + for (int i = 0; i < n; ++i) { |
| 46 | + trappedWater += |
| 47 | + std::max(0, std::min(leftMax[i], rightMax[i]) - heights[i]); |
| 48 | + } |
| 49 | + |
| 50 | + return trappedWater; |
| 51 | +} |
| 52 | + |
| 53 | +} // namespace dynamic_programming |
| 54 | + |
| 55 | +/** |
| 56 | + * @brief Self-test implementations |
| 57 | + * @returns void |
| 58 | + */ |
| 59 | +static void test() { |
| 60 | + std::vector<int> heights1 = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; |
| 61 | + assert(dynamic_programming::trappedRainwater(heights1) == 6); |
| 62 | + |
| 63 | + std::vector<int> heights2 = {3, 0, 0, 2, 0, 4}; |
| 64 | + assert(dynamic_programming::trappedRainwater(heights2) == 10); |
| 65 | + |
| 66 | + std::vector<int> heights3 = {1, 2, 3, 4, 5}; |
| 67 | + assert(dynamic_programming::trappedRainwater(heights3) == 0); |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * @brief Main function |
| 72 | + * @returns 0 on exit |
| 73 | + */ |
| 74 | +int main() { |
| 75 | + test(); // run self-test implementations |
| 76 | + return 0; |
| 77 | +} |
0 commit comments