-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday30.cpp
More file actions
70 lines (57 loc) · 1.81 KB
/
Copy pathday30.cpp
File metadata and controls
70 lines (57 loc) · 1.81 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
You are given an array of non-negative integers that represents a two-dimensional elevation map where each element is unit-width wall and the integer is the height. Suppose it will rain and all spots between two walls get filled up.
Compute how many units of water remain trapped on the map in O(N) time and O(1) space.
For example, given the input [2, 1, 2], we can hold 1 unit of water in the middle.
Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in the second, and 3 in the fourth index (we cannot hold 5 since it would run off to the left), so we can trap 8 units of water.
*/
#include <gtest/gtest.h>
using namespace std;
/**
* Idea: Two pointers
* TC: o(n)
* SC: o(1)
*/
int rain(vector<int> vector)
{
int left = 0;
int max_left = left;
int right = vector.size() - 1;
int max_right = right;
int count = 0;
while (left < right)
{
if (vector.at(max_left) < vector.at(max_right))
{
if (vector.at(left) > vector.at(max_left))
max_left = left;
else
count += vector.at(max_left) - vector.at(left);
left++;
}
else
{
if (vector.at(right) > vector.at(max_right))
max_left = right;
else
count += vector.at(max_right) - vector.at(right);
right--;
}
}
return count;
}
TEST(RAIN, rain)
{
vector<int> r{3, 0, 1, 3, 0, 5};
vector<int> r2{2, 1, 2};
vector<int> r3{2, 0, 3, 1, 1, 0, 2};
EXPECT_EQ(rain(r), 8);
EXPECT_EQ(rain(r2), 1);
EXPECT_EQ(rain(r3), 6);
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}