11. Container With Most Water
Intuition
Give a list of number, find maximum volumn between two entries given that $$ \text{Volumn} = \min(\text{nums}[i],\text{nums}[j]) \times (j - i) $$ for \(0 \le i < j < \text{len}\)
Approach
Use Sliding Windows approach.
- Step 1:
- creat two pointer
lowandhighpointing to the start and end position of the given array. - creat variable
maxto store the max value we ever get and keep updating max during loop iteration.
- creat two pointer
- Step 2: During loop iteration,
- If
height[low] < height[high], movelowpointer until current height is less than or equal toheight[low]. - If
height[low] >= height[high], movehighpointer until current height is less than or equal toheight[height].
- If
- Hence, in every loop, we will get a higher height than the previous one. The loop iteration ends when two pointer encounters. Finally, we return the maximum value of volumn we get during iteration.
Complexity
- Time complexity: \(O(n)\)
- Space complexity: \(O(1)\)