problem
42. Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
approach 1 TLE
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int ans = 0;
for(int i=0; i<n; i++){
int left_max = 0, right_max = 0;
for(int t = i; t>=0; t--)
left_max = max(left_max, height[t]);
for(int t = i; t<n; t++)
right_max = max(right_max, height[t]);
ans += min(left_max, right_max) - height[i];
}
return ans;
}
};
time complexity
:
O
(
n
2
)
O(n^2)
O(n2)
space complexity
:
O
(
1
)
O(1)
O(1)
approach 2 DP
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
vector<int> left_max(n), right_max(n);
left_max[0] = height[0];
right_max[n-1] = height[n-1];
int ans = 0;
for(int i=1; i<n; i++){
left_max[i] = max(left_max[i-1], height[i]);
right_max[n-i-1] = max(right_max[n-i], height[n-i-1]);
}
for(int i=0; i<n; i++){
ans += min(left_max[i], right_max[i]) - height[i];
}
return ans;
}
};
time complexity
:
O
(
n
)
O(n)
O(n)
space complexity
:
O
(
n
)
O(n)
O(n)
approach 3 two point
class Solution {
public:
int trap(vector<int>& height)
{
int n = height.size();
int res = 0;
int left_max = 0, right_max = 0;;
int left = 0, right = n-1;
while(left <= right){
if(height[left] >= height[right]){
if(height[right] >= right_max)
right_max = height[right];
else res += right_max - height[right];
right--;
}else{
if(height[left] >= left_max)
left_max = height[left];
else res += left_max - height[left];
left++;
}
}
return res;
}
};
time complexity
:
O
(
n
)
O(n)
O(n)
space complexity
:
O
(
1
)
O(1)
O(1)
wrong approach
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int ans = 0;
int left_max = height[0], right_max = 0;
int right_ind;
for(int i=0; i<n; i++){
if(height[i] >= right_max){
right_max = height[i];
right_ind = i;
}
}
for(int i=0; i<n; i++){
left_max = max(left_max, height[i]);
if(i == right_ind){
left_max = right_max;
right_max = 0;
for(int t=i; t<n; t++){
if(height[t] >= right_max){
right_max = height[i];
right_ind = t;
}
}
}
ans += min(left_max, right_max) - height[i];
}
return ans;
}
};