Skip to content

Commit fbfdd14

Browse files
Chris WuChris Wu
authored andcommitted
no message
1 parent 0cc1408 commit fbfdd14

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

problems/container-with-most-water.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
`l` and `r` are the points on width that form the area.
3+
The height on `l` is `H[l]` and `r` is `H[r]`.
4+
The area that form by `l` and `r` is `(r-l)*min(H[r], H[l])`.
5+
6+
We are going to calculate the area everytime we move `l` or `r`.
7+
And maintain the `ans`, which is the max of all area.
8+
9+
Now, we put `l` and `r` at the beginning and at the end of the array.
10+
We calculate the area and update `ans`, move `l` or `r` inward.
11+
How are we going to find a larger area with shorter width that form by `l` and `r`?
12+
The answer is, we move the `l` or `r` with shorter `H[l]` or `H[r]`, so we might get a larger `min(H[r], H[l])`, which leads to possibly larger area.
13+
14+
By doing this, we now have a new pair of `l` and `r`.
15+
We calculate the area and update `ans`, move `l` or `r` inward.
16+
17+
...
18+
19+
We repeat the process until `l` and `r` collapse.
20+
So by repeatedly moving `l` and `r` inward, we can run through all the shorter width that might form area larger than `ans`.
21+
"""
22+
class Solution(object):
23+
def maxArea(self, H):
24+
r, l = len(H)-1, 0
25+
ans = float('-inf')
26+
27+
while r>l:
28+
ans = max(ans, (r-l)*min(H[r], H[l]))
29+
if H[r]>H[l]:
30+
l = l+1
31+
else:
32+
r = r-1
33+
return ans
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution(object):
2+
def twoSum(self, numbers, target):
3+
memo = {}
4+
for i, n in enumerate(numbers):
5+
if target-n in memo:
6+
return [memo[target-n]+1, i+1]
7+
memo[n] = i
8+
9+
"""
10+
We put `l` and `r` at the beginning and at the end of the array.
11+
Everytime with new pair of `l` and `r`, we check if its sum is target. If true, return the answer.
12+
If the sum is larger than the target, we need to reduce the sum, and the only way to do that is to move `r` leftward, since `l` is already at the leftmost.
13+
If the sum is smaller than the target, we need to increase the sum, and the only way to do that is to move `l` rightward, since `r` is already at the rightmost.
14+
15+
The time complexity is O(N).
16+
The space complexity is O(1).
17+
"""
18+
class Solution(object):
19+
def twoSum(self, numbers, target):
20+
r, l = len(numbers)-1, 0
21+
while r>l:
22+
if numbers[r]+numbers[l]==target:
23+
return [l+1, r+1]
24+
elif numbers[r]+numbers[l]>target:
25+
r = r-1
26+
else:
27+
l = l+1
28+
return []

0 commit comments

Comments
 (0)