Original title link
Title description
给出一个整数n,将n分解为至少两个整数之和,使得这些整数的乘积最大化,输出能够获得的最大的乘积。
例如:
2=1+1,输出1;
10=3+3+4,输出36。
Example
输入:
10
输出:
36
Reference Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int sum = 1;
// 多分解几个数就会发现,全分解为2或者3时,乘积最大
if (n <= 0) {
System.out.print(0);
} else if (n > 0 && n <= 2) {
System.out.print(1);
} else if (n == 3) {
System.out.print(3);
} else if (n == 4) {
System.out.print(4);
} else {
while (n > 4) {
sum *= 3;
n = n - 3;
}
// 这时n的值可能为2,3,4
if (n >= 2)
sum *= n;
System.out.print(sum);
}
}
}
to sum up
You can use 动态规划
answers to this kind of questions, so as to keep changing. The premise is that you have a certain degree of dynamic programming 熟悉度
. At the same time, it can also be 分析其规律
solved, solving specific problems 效率更高
.