-
Notifications
You must be signed in to change notification settings - Fork 1
/
IntegerBreak.java
43 lines (40 loc) · 1.21 KB
/
IntegerBreak.java
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
package com.hncboy;
/**
* @author hncboy
* @date 2021/9/23 11:37
* @description 343.整数拆分
*
* 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
*
* 示例 1:
* 输入: 2
* 输出: 1
* 解释: 2 = 1 + 1, 1 × 1 = 1。
*
* 示例 2:
* 输入: 10
* 输出: 36
* 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
* 说明: 你可以假设 n 不小于 2 且不大于 58。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/integer-break
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class IntegerBreak {
public static void main(String[] args) {
IntegerBreak integerBreak = new IntegerBreak();
assert integerBreak.integerBreak(2) == 1;
assert integerBreak.integerBreak(10) == 36;
}
private int integerBreak(int n) {
int[] dp = new int[n + 1];
dp[2] = 1;
for (int i = 3; i <= n; i++) {
for (int j = 2; j < i; j++) {
dp[i] = Math.max(dp[i], Math.max(j * (i - j), j * dp[i - j]));
}
}
return dp[n];
}
}