forked from deepaktalwardt/interview-prep-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwater-area.cpp
More file actions
34 lines (31 loc) · 837 Bytes
/
water-area.cpp
File metadata and controls
34 lines (31 loc) · 837 Bytes
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
#include <vector>
#include <numeric>
using namespace std;
int waterArea(vector<int> heights) {
// Write your code here.
if (heights.size() <= 2) return 0;
vector<int> leftMax(heights.size(), 0);
vector<int> rightMax(heights.size(), 0);
int leftMaxSoFar = 0;
int rightMaxSoFar = 0;
for (int i = 0; i < heights.size(); i++) {
leftMax[i] = leftMaxSoFar;
if (heights[i] > leftMaxSoFar) {
leftMaxSoFar = heights[i];
}
}
for (int j = heights.size() - 1; j >= 0; j--) {
rightMax[j] = rightMaxSoFar;
if (heights[j] > rightMaxSoFar) {
rightMaxSoFar = heights[j];
}
}
int waterLevel = 0;
for (int k = 0; k < heights.size(); k++) {
int minLevel = min(leftMax[k], rightMax[k]);
if (heights[k] < minLevel) {
waterLevel += minLevel - heights[k];
}
}
return waterLevel;
}