Leetcode : 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.
Example 1
Input
height = [1,8,6,2,5,4,8,3,7]
Output
49
Example 2
Input
height = [1,1]
Output
1
Example 3
Input
height = [4,3,2,1,4]
Output
16
Example 4
Input
height = [1,2,1]
Output
2
Use two-pointer algorithm to calculate the maximum amount of water within the vertical lines. Set two variables left and right, and multiply smaller vertical line min(height[left], height[right]) to the number of spaces in between - (right - left)
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
maxArea = 0
while left < right:
maxArea = max(maxArea, (right - left) * min(height[left], height[right]))
if height[left] < height[right]:
left = left + 1
else:
right = right - 1
return maxArea
Result
Runtime: 152 ms
Memory Usage: 16.3 MB
Runtime Beats 61.64% of Python Submission
First and foremost, I commend the author for shedding light on the fact that car seats are not just accessories but essential safety devices. The statistics mentioned in the article are truly alarming, and they serve as a wake-up call for all parents and caregivers. a fantastic read find this Visit us read this article click here now.