left
pointer to 0 and right
pointer to the last index of the array.left_max
and right_max
to 0.ans
to 0 to store the total water trapped.left
is less than right
, do:
a. If height[left]
is less than height[right]
, then:
i. If height[left]
is greater than or equal to left_max
, update left_max
.
ii. Else, add left_max - height[left]
to ans
.
iii. Increment left
.
b. Else:
i. If height[right]
is greater than or equal to right_max
, update right_max
.
ii. Else, add right_max - height[right]
to ans
.
iii. Decrement right
.ans
.