0042. 接雨水 #49
utterances-bot
started this conversation in
Comments
Replies: 0 comments 1 reply
-
附C++代码附上动态规划的解法,左右数组 const int N = 2e4+5;
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int leftMax[N] = {0};
int rightMax[N] = {0};
for(int i = 1; i < n-1; ++i)
leftMax[i] = leftMax[i-1] > height[i-1] ? leftMax[i-1] : height[i-1];
for(int i = n-2; i > 0; --i)
rightMax[i] = rightMax[i+1] > height[i+1] ? rightMax[i+1] : height[i+1];
int res = 0, minheight;
for(int i = 1; i < n-1; ++i) {
minheight = leftMax[i] <= rightMax[i] ? leftMax[i] : rightMax[i];
if(minheight > height[i]) res += (minheight-height[i]);
}
return res;
}
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
0042. 接雨水 | 算法通关手册
https://algo.itcharge.cn/Solutions/0001-0099/trapping-rain-water/
Beta Was this translation helpful? Give feedback.
All reactions