Problem
-
We’re given an input array containing
height
values whereheights[i]
represent the height of the bar. -
Our function can choose any two bars to form a container. Return the maximum amount of water a container can store.
Example
Approach 1
Visualize the problem
Solve without code
- Look at left and right of input
- Get the min height of both since we need even heights
- Calculate the area
- Ask ourselves if the new area is great than the current
- If our left is less than our right bar then we move it by one otherwise we move right by one
Solve with code
- Create
l
andr
pointers. - Create a result variable to hold our current max result
- Create a while loop with the condition of
while l < r
- Calculate area by finding the width
r - l
and the heightmin(heights[r],heights[l]
- This will give us the min height which we can multiply by the width
- If our left pointer is smaller than our right we increase its index, otherwise subtract the right index by one
- Calculate area by finding the width
- return our result
Implementation
Complexity Analysis
- Time Complexity:
- Space Complexity: