From f847a77884474390d4c963e386d8d4e3f9f9d06c Mon Sep 17 00:00:00 2001 From: ImAlpha Date: Thu, 21 Sep 2023 21:15:17 -0700 Subject: [PATCH] Added O(N) Solution with comments --- .../11_Container_With_Most_Water.py | 37 +++++++++++++------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/NeetCodeRoadmap/Two_Pointers/11_Container_With_Most_Water.py b/NeetCodeRoadmap/Two_Pointers/11_Container_With_Most_Water.py index d715426..a25886c 100644 --- a/NeetCodeRoadmap/Two_Pointers/11_Container_With_Most_Water.py +++ b/NeetCodeRoadmap/Two_Pointers/11_Container_With_Most_Water.py @@ -3,20 +3,33 @@ def maxArea(height): :type height: List[int] :rtype: int """ - n = len(height) - container = [] + # n = len(height) + # container = [] - # Handle edge-case - if n == 2: - return min(height) + # # Handle edge-case + # if n == 2: + # return min(height) - for i in range(n): - for j in range(i+1,n): - index = min(height[i], height[j]) - dist = j-i - container.append(index*dist) - return max(container) - # return container + # for i in range(n): + # for j in range(i+1,n): + # index = min(height[i], height[j]) + # dist = j-i + # container.append(index*dist) + # return max(container) + # # return container + + # Solution O(N) https://youtu.be/Kb20p6zy_14?si=6B86Iwh0-O_Cww0Q + max_area = 0 + l = 0 + r = len(height) - 1 + while l < r: + area = (r - l) * min(height[r], height[l]) + max_area = max(max_area, area) + if height[l] < height[r]: # Check to see if left or right is smaller + l += 1 + else: + r -= 1 + return max_area print(maxArea([1,8,6,2,5,4,8,3,7])) #Output: 49 print(maxArea([1,2,1])) #Output: 2