Created
October 29, 2019 16:26
-
-
Save vitkarpov/8e355ee24e9bd5b740f84a411f01df43 to your computer and use it in GitHub Desktop.
42. Trapping Rain Water
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int trap(const vector<int>& h) { | |
int n = h.size(); | |
vector<int> left_max(n + 1); | |
vector<int> right_max(n + 1); | |
for (int i = 1; i <= n; i++) { | |
left_max[i] = max(left_max[i - 1], h[i - 1]); | |
} | |
for (int i = n - 2; i >= 0; i--) { | |
right_max[i] = max(right_max[i + 1], h[i + 1]); | |
} | |
int ans = 0; | |
for (int i = 0; i < n; i++) { | |
ans += max(0, min(left_max[i], right_max[i]) - h[i]); | |
} | |
return ans; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment