TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
trapped_rainwater.cpp
Go to the documentation of this file.
1
11#include <algorithm>
12#include <cassert>
13#include <cstddef>
14#include <cstdint>
15#include <vector>
16
17/*
18 * @namespace
19 * @brief Dynamic Programming Algorithms
20 */
21namespace dynamic_programming {
27uint32_t trappedRainwater(const std::vector<uint32_t>& heights) {
28 std::size_t n = heights.size();
29 if (n <= 2)
30 return 0; // No water can be trapped with less than 3 walls
31
32 std::vector<uint32_t> leftMax(n), rightMax(n);
33
34 // Calculate the maximum height of wall to the left of each wall
35 leftMax[0] = heights[0];
36 for (std::size_t i = 1; i < n; ++i) {
37 leftMax[i] = std::max(leftMax[i - 1], heights[i]);
38 }
39
40 // Calculate the maximum height of wall to the right of each wall
41 rightMax[n - 1] = heights[n - 1];
42 for (std::size_t i = n - 2; i < n; --i) {
43 rightMax[i] = std::max(rightMax[i + 1], heights[i]);
44 }
45
46 // Calculate the trapped rainwater between walls
47 uint32_t trappedWater = 0;
48 for (std::size_t i = 0; i < n; ++i) {
49 trappedWater +=
50 std::max(0u, std::min(leftMax[i], rightMax[i]) - heights[i]);
51 }
52
53 return trappedWater;
54}
55
56} // namespace dynamic_programming
57
62static void test() {
63 std::vector<uint32_t> test_basic = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
64 assert(dynamic_programming::trappedRainwater(test_basic) == 6);
65
66 std::vector<uint32_t> test_peak_under_water = {3, 0, 2, 0, 4};
67 assert(dynamic_programming::trappedRainwater(test_peak_under_water) == 7);
68
69 std::vector<uint32_t> test_bucket = {5, 1, 5};
70 assert(dynamic_programming::trappedRainwater(test_bucket) == 4);
71
72 std::vector<uint32_t> test_skewed_bucket = {4, 1, 5};
73 assert(dynamic_programming::trappedRainwater(test_skewed_bucket) == 3);
74
75 std::vector<uint32_t> test_empty = {};
76 assert(dynamic_programming::trappedRainwater(test_empty) == 0);
77
78 std::vector<uint32_t> test_flat = {0, 0, 0, 0, 0};
79 assert(dynamic_programming::trappedRainwater(test_flat) == 0);
80
81 std::vector<uint32_t> test_no_trapped_water = {1, 1, 2, 4, 0, 0, 0};
82 assert(dynamic_programming::trappedRainwater(test_no_trapped_water) == 0);
83
84 std::vector<uint32_t> test_single_elevation = {5};
85 assert(dynamic_programming::trappedRainwater(test_single_elevation) == 0);
86
87 std::vector<uint32_t> test_two_point_elevation = {5, 1};
88 assert(dynamic_programming::trappedRainwater(test_two_point_elevation) ==
89 0);
90
91 std::vector<uint32_t> test_large_elevation_map_difference = {5, 1, 6, 1,
92 7, 1, 8};
94 test_large_elevation_map_difference) == 15);
95}
96
101int main() {
102 test(); // run self-test implementations
103 return 0;
104}
Dynamic Programming algorithms.
uint32_t trappedRainwater(const std::vector< uint32_t > &heights)
Function to calculate the trapped rainwater.
static void test()
Self-test implementations.
int main()
Main function.