Container With Most Water
Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Solution
Use two pointers, one at the start and one at the end. Calculate the area between them. Move the pointer with the smaller height inwards. Repeat until the pointers meet.
Implementation
Pseudocode
- Initialize two pointers, one at the start and one at the end.
- Initialize a variable to store the max volume.
- While the pointers don’t meet:
- Calculate the width and height of the container.
- Calculate the volume of the container.
- Update the max volume.
- Move the pointer with the smaller height inwards.
- Return the max volume.