纯数学做法:
x1+x2+...+xn ≥ n sqrt_{n}(x1*x2...*xn),当且仅当 x1=x2=..=xn时等号成立。
所以为了取到最大值,我们要尽量拆分成几个相等的值。
之后的问题便是,要拆分成几个呢?
假设拆分成n个实数,那么设每一个数为x,则一共有n/x个数。
设它们的积为f(x),则f(x)=x(n/x),求f(x)的最大值,求导。
f′(x)=(n/x2) * x(n/x) * (1-lnx)
当x=e时取极大值。
而我们题目里规定x为整数,那么我们只需要取的x越靠近e越好。那么2<e<3,而且e=2.71828...,所以取3是最好的,如果取不到3就取2。
幂运算复杂度为O(lgn),所以这个算法复杂度为O(lgn)。
class Solution { public int integerBreak(int n) { if(n == 2) return 1; else if(n == 3) return 2; else if(n%3 == 0) return (int)Math.pow(3, n/3); else if(n%3 == 1) return 2 * 2 * (int)Math.pow(3, (n - 4) / 3); else return 2 * (int)Math.pow(3, n/3); } }