Complete the code to initialize the total trapped water to zero.
int trap(vector<int>& height) {
int water = [1];
return water;
}We start counting trapped water from zero because initially no water is trapped.
Complete the code to find the maximum height to the left of each bar.
vector<int> leftMax(height.size()); leftMax[0] = height[0]; for (int i = 1; i < height.size(); i++) { leftMax[i] = [1](leftMax[i - 1], height[i]); }
We use max to keep track of the highest bar on the left side.
Fix the error in the loop that calculates trapped water by choosing the correct function to find the minimum of leftMax and rightMax.
for (int i = 0; i < height.size(); i++) { water += [1](leftMax[i], rightMax[i]) - height[i]; }
We use min because water trapped depends on the shorter boundary between left and right.
Fill both blanks to correctly compute the maximum height to the right of each bar.
vector<int> rightMax(height.size()); rightMax[height.size() - 1] = height[height.size() - 1]; for (int i = height.size() - 2; i >= 0; i--) { rightMax[i] = [1](rightMax[i [2] 1], height[i]); }
We use max to find the tallest bar on the right, and i + 1 to refer to the rightMax already computed for the right side.
Fill all three blanks to complete the function that calculates total trapped water.
int trap(vector<int>& height) {
int water = 0;
vector<int> leftMax(height.size()), rightMax(height.size());
leftMax[0] = height[0];
for (int i = 1; i < height.size(); i++) {
leftMax[i] = [1](leftMax[i - 1], height[i]);
}
rightMax[height.size() - 1] = height[height.size() - 1];
for (int i = height.size() - 2; i >= 0; i--) {
rightMax[i] = [2](rightMax[i + 1], height[i]);
}
for (int i = 0; i < height.size(); i++) {
water += [3](leftMax[i], rightMax[i]) - height[i];
}
return water;
}Use max to find leftMax and rightMax, and min to find the limiting height for trapped water.
