Created
March 8, 2022 20:33
-
-
Save doyedele1/302ec85ca49762c392e559586a6de33f to your computer and use it in GitHub Desktop.
Container with Most Water
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Explanation: | |
- Intuitvely, we can find the possible areas for each pair of heights | |
- For each pair, we check the area by multiplying the width to the height without spill over. We need to consider the minimum height between the pair. | |
- However, can we reduce the number of times we find the possible areas for every pair of the heights which is caused by the minimum height in each pair? | |
- Yes, we can. We can have two pointers at both endpoints and perform the area of the ractangle. | |
- When the height is minimum for a left pointer, we can move to the pointer to the right and when the height is minimum for a right pointer, we move the pointer to the left to the right. This is done to look for the next possible maximum height. | |
- TC: O(n), SC: O(1) | |
''' | |
class Solution: | |
def maxArea(self, height: List[int]) -> int: | |
ans = 0 | |
i = 0 | |
j = len(height) - 1 | |
while i < j: | |
area_of_rectangle = (j - i) * (min(height[i], height[j])) | |
ans = max(ans, area_of_rectangle) | |
if height[i] < height[j]: | |
i += 1 | |
else: j -= 1 | |
return ans |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment