-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnc-TwoPointer-ContainerWithMostWater.py
More file actions
69 lines (50 loc) · 1.54 KB
/
nc-TwoPointer-ContainerWithMostWater.py
File metadata and controls
69 lines (50 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3
'''Container With Most Water
You are given an integer array 'heights' where heights[i] represents the height
of the i-th bar.
You may choose any two bars to form a container. Return the maximum amount of water a container can store.
Example 1:
Input: height = [1,7,2,5,4,7,3,6]
Output: 36
Example 2:
Input: height = [2,2,2]
Output: 4
Constraints:
2 <= height.length <= 1000
0 <= height[i] <= 1000
Recommended Time & Space Complexity
You should aim for a solution with O(n) time and O(1) space, where n is the
size of the input array.
Notes:
So, any to elements, find the area by:
(height) * (width)
(larger of the elements) * (difference of the two indexes)
'''
# import time
class Solution:
def maxArea(self, heights: list[int]) -> int:
left = 0
right = len(heights) -1
maxArea = 0
while left < right:
height = min(heights[left], heights[right])
width = right - left
area = height * width
maxArea = max(maxArea, area)
print([left, right],
[heights[left], heights[right]],
height,
width,
area,
maxArea)
if heights[left] < heights[right]:
left += 1
else:
right -= 1
return maxArea
# heights = [1,7,2,5,4,7,3,6] # Output: 36
heights = [2,2,2] # Output: 4
solution = Solution()
result = solution.maxArea(heights)
print("The final result is:")
print(result)