題目:
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.java
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).less
Note: you may assume that n is not less than 2.code
解答:
這裏我提供了兩個辦法,一種是我用dp的辦法解的,還有一種是參考別人的數學解法:
DP解法:get
//State: f[i] is when sum is i the largest product we can get //Function: f[i] = max(f[i - j] * j), i >= 2, i - j >= 1 //Initialize: f[1] = f[2] = 1; //Result: f[n] public int integerBreak(int n) { int[] f = new int[n + 1]; Arrays.fill(f, 1); for (int i = 3; i <= n; i++) { for (int j = 1; j < i; j++) { //注意,f[i]的最大值是由至少兩個數的乘積組成的,可是他自己i這個值在比i大的數的乘積中,也能夠單獨做爲一個因子出現,因此要加上跟這種狀況的比較,即(i - j) * j f[i] = Math.max(f[i], Math.max(f[i - j] * j, (i - j) * j)); } } return f[n]; }
數學解法:數學
//A more mathematic solution //We can prove that when N is even, N/2 * N/2 is largest; when N is odd, (N - 1)/2 * (N + 1)/2 is the largest //Also we have N/2 * N/2 > N --> N > 4 // (N - 1)/2 * (N + 1)/2 > N --> N >= 5 //So when N > 4, we can do the calculation public int integerBreak(int n) { if (n == 2) return 1; if (n == 3) return 2; int result = 1; while (n > 4) { result *= 3; n -= 3; } result *= n; return result; }