GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Arrays/container_with_most_water.py at master · chy-learn/coding-problems

Expand file tree

/

container_with_most_water.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
51 lines (38 loc) · 1.24 KB
/

container_with_most_water.py

Copy path

File metadata and controls

51 lines (38 loc) · 1.24 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
'''
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 line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
=========================================
Playing with pointers from both sides, eliminate smaller heights and search for a bigger height.
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
def max_area(height):
l = 0
r = len(height) - 1
max_height = 0
while l < r:
left = height[l]
right = height[r]
current_height = min(left, right) * (r - l)
max_height = max(max_height, current_height)
# take the smaller side and search for a bigger height on that side
if left < right:
while (l < r) and (left >= height[l]):
l += 1
else:
while (l < r) and (right >= height[r]):
r -= 1
return max_height
###########
# Testing #
###########
# Test 1
# Correct result => 49
print(max_area([1, 8, 6, 2, 5, 4, 8, 3, 7]))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.