-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
max_water_trappable.cc
44 lines (38 loc) · 1.32 KB
/
max_water_trappable.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <algorithm>
#include <iterator>
#include <limits>
#include <vector>
#include "test_framework/generic_test.h"
using std::distance;
using std::numeric_limits;
using std::vector;
template <typename Iter>
int TrappingWaterTillEnd(Iter, Iter);
int CalculateTrappingWater(const vector<int>& heights) {
// Finds the index with maximum height.
int max_h =
distance(begin(heights), max_element(begin(heights), end(heights)));
return TrappingWaterTillEnd(begin(heights), begin(heights) + max_h) +
TrappingWaterTillEnd(rbegin(heights),
rbegin(heights) + size(heights) - 1 - max_h);
}
// Assume end is maximum height.
template <typename Iter>
int TrappingWaterTillEnd(Iter begin, Iter end) {
int sum = 0, highest_level_seen = numeric_limits<int>::min();
for (Iter iter = begin; iter != end; ++iter) {
if (*iter >= highest_level_seen) {
highest_level_seen = *iter;
} else {
sum += highest_level_seen - *iter;
}
}
return sum;
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"heights"};
return GenericTestMain(args, "max_water_trappable.cc",
"max_water_trappable.tsv", &CalculateTrappingWater,
DefaultComparator{}, param_names);
}