Skip to content

Commit 70d9981

Browse files
committed
Update integer-break.py
1 parent 9a8e03c commit 70d9981

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

Python/integer-break.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,22 @@ def integerBreak(self, n):
5656
else: # n = 3Q + 4, the max is 3^Q * 2^2
5757
res = 3 ** (n // 3 - 1) * 4
5858
return res
59+
60+
# Time: O(n)
61+
# Space: O(logn)
62+
# DP solution.
63+
class Solution2(object):
64+
def integerBreak(self, n):
65+
"""
66+
:type n: int
67+
:rtype: int
68+
"""
69+
if n < 4:
70+
return n - 1
71+
72+
# integerBreak(n) = max(integerBreak(n - 2) * 2, integerBreak(n - 3) * 3)
73+
res = [0] * 4
74+
res[1 % 4], res[2 % 4], res[3 % 4] = 1, 2, 3
75+
for i in xrange(4, n + 1):
76+
res[i % 4] = max(res[(i - 2) % 4] * 2, res[(i - 3) % 4] * 3)
77+
return res[n % 4]

0 commit comments

Comments
 (0)