您的位置:首页 > 其它

343. Integer Break

2018-01-04 22:48 239 查看

343. Integer Break

题目描述:Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

Note: You may assume that n is not less than 2 and not larger than 58.

题目大意:给定一个正整数n,分解为至少两个以上的数相加使得其和为n,找出所有分解中的最大的积。

思路:n = 2 max = 1(1 + 1)

n = 3 max = 2(1 + 2)

n = 4 max = 4(2 + 2)

n = 5 max = 6(2 + 3)

n = 6 max = 9(3 + 3)

n = 7 max = 12(3 + 2 + 2)

n = 8 max = 16(2 + 2 + 2 + 2)

n = 9 max = 27(3 + 3 + 3)

n = 10 max = 36(2 + 2 + 3 + 3)

大致也发现了一点规律,我们都分解为1 2 3这样的组合。

很简单,如果组合为4,4又可以分解为2 + 2,如果组合为5,5又可以分解为2 + 3。

代码1:

public static int integerBreak(int n) {
if (n <= 3) {
return n - 1;
}
int[] dp = new int[n+1];
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
for(int i=4;i<=n;i++) {
dp[i] = Math.max(2 * dp[i - 2],3 * dp[i - 3]);
}
return dp
;
}


代码2:

package DP;

/**
* @author OovEver
* 2018/1/4 22:32
*/
public class LeetCode343 {
public static int integerBreak(int n) {
int[] dp = new int[n + 1];
dp[1] = 1;
for(int i=2;i<=n;i++) {
for(int j=1;j<i;j++) {
dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * Math.max(i - j, dp[i - j]));
}
}
return dp
;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: