Saturday, July 31, 2021

Container With Most Water

Problem:
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 line i are 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.

Notice, that you may not slant the container.

Example,


Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 








Approach:
The first thing is that how can we calculate the area, which would be height*width. First, let's try to visualize,



We need to calculate the maximum area,One thing is clear that,
    area = height*width
=>area = min(height[left], height[right]) * (right-left)

Yes, you get right, this problem can be solved using the two-pointer method.

Putting the left pointer in the left and right pointer in the rightmost position, we will calculate the area. After checking which side is greater-smaller, we can move our pointer. That's all we need to do about this problem.

See the code for a better understanding.


No comments:

Post a Comment