another classic problem.

use double direction two pointers.

class Solution {
    public int trap(int[] height) {
        
        int res = 0;
        int left = 0;
        int right = height.length - 1;
        int leftMax = 0;
        int rightMax = 0;
        while (left < right) {
            if (height[left] <= height[right]) { //left is the control variable
                leftMax = Math.max(leftMax, height[left]);
                res += leftMax - height[left];
                left++;
            } else if (height[left] > height[right]) {
                rightMax = Math.max(rightMax, height[right]);
                res += rightMax - height[right];
                right--;
            }
        }
        return res;
    }
}

just pay attention to a point: that when height[left] == height[right], it doesn’t matter if we move left or right.