-
Notifications
You must be signed in to change notification settings - Fork 43
/
water-and-jug-problem.py
40 lines (35 loc) · 1018 Bytes
/
water-and-jug-problem.py
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
# V1 : DEV
# V2
# https://blog.csdn.net/fuxuemingzhu/article/details/83574784
# given equation : z = m * x + n * y
# find if it has solution integer pair (m, n )
class Solution(object):
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
return z == 0 or (x + y >= z and z % self.gcd(x, y) == 0)
def gcd(self, x, y):
return x if y == 0 else self.gcd(y, x % y)
# V3
# Time: O(logn), n is the max of (x, y)
# Space: O(1)
class Solution(object):
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
# The problem is to solve:
# - check z <= x + y
# - check if there is any (a, b) integers s.t. ax + by = z
return z == 0 or ((z <= x + y) and (z % gcd(x, y) == 0))