Brute Force
1 | class Solution { |
Remarks:
- TC: $O(n^2)$, SC: $O(1)$
- Cannot pass: out of time
Dynamic Programming
1 | class Solution { |
Remarks:
- Key Methodology: for any bar
i
,vol[i] = min(highest_on_the_left, highest_on_the_right) - height[i]
. - The highest on the left for
i
will bemax(height[i], highest_on_the_left[i - 1])
. Same for the right side. - TC: $O(n)$, SC: $O(n)$
Two Pointers
1 | class Solution { |
- TC: $O(n)$, SC: $O(1)$
- Main idea: if we know the left one is smaller than the right, because the water volume is based on the lower bar, we can simply confirm the volum of the current bar is
leftMax - height[left];
.