- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinteger_break.py
More file actions
Latest commit
25 lines (21 loc) · 888 Bytes
/
Copy pathinteger_break.py
File metadata and controls
25 lines (21 loc) · 888 Bytes
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
importunittest
# 能否找到和为n的一组正整数,使得他们的乘积最大
# 例如 3+3+4=10,和为10的数组中最大乘积是36
classSolution(unittest.TestCase):
TEST_CASES= [
(2, 1),
(10, 36)
]
deftest_integer_break(self):
forn, productinself.TEST_CASES:
self.assertEqual(product, self.integer_break(n))
@staticmethod
definteger_break(n: int):
dp= [0] * (n+1)
# 只有当整数大于2时才能找到划分点j
foriinrange(2, n+1):
forjinrange(i):
# 将i拆分成j和i-j的和,且i-j不再拆分成多个正整数,此时的乘积是jx(i-j)
# 将i拆分成j和i-j的和,且i-j继续拆分成多个正整数,此时的乘积是jxdp[i-j]
dp[i] =max(dp[i], j* (i-j), j*dp[i-j])
returndp[n]