selected_coding_interview/docs/343. 整数拆分.md
$$ n = n_1 + n_2 + ... + n_a $$
$$ \max(n_1 \times n_2 \times ... \times n_a) $$
以下数学推导总体分为两步:① 当所有拆分出的数字相等时,乘积最大。② 最优拆分数字为 $3$ 。
$$ \frac{n_1 + n_2 + ... + n_a}{a} \geq \sqrt[a]{n_1 n_2 ... n_a} $$
推论一: 若拆分的数量 $a$ 确定, 则 各拆分数字相等时 ,乘积最大。
$$ x^a = x^{\frac{n}{x}} = (x^{\frac{1}{x}})^n $$
$$ \begin{aligned} \ln y & = \frac{1}{x} \ln x & \text{取对数} \ \frac{1}{y} \dot {y} & = \frac{1}{x^2} - \frac{1}{x^2} \ln x & \text{对 $x$ 求导} \ & = \frac{1 - \ln x}{x^2} \ \dot {y} & = \frac{1 - \ln x}{x^2} x^{\frac{1}{x}} & \text{整理得}\end{aligned} $$
$$ \dot {y}\begin{cases} > 0 & , x \in [- \infty, e) \ < 0 & , x \in (e, \infty] \\end{cases} $$
$$ y(3) = 3^{1/3} \approx 1.44 \ y(2) = 2^{1/2} \approx 1.41 $$
$$ [y(3)]^6 = (3^{1/3})^6 = 9 \ [y(2)]^6 = (2^{1/2})^6 = 8 $$
推论二: 将数字 $n$ 尽可能以因子 $3$ 等分时,乘积最大。
{:width=600}
a 和 b 使用常数大小额外空间。Python 中常见有三种幂计算函数:
*和pow()的时间复杂度均为 $O(\log a)$ ;而math.pow()始终调用 C 库的pow()函数,其执行浮点取幂,时间复杂度为 $O(1)$ 。
class Solution:
def integerBreak(self, n: int) -> int:
if n <= 3: return n - 1
a, b = n // 3, n % 3
if b == 0: return int(math.pow(3, a))
if b == 1: return int(math.pow(3, a - 1) * 4)
return int(math.pow(3, a) * 2)
class Solution {
public int integerBreak(int n) {
if(n <= 3) return n - 1;
int a = n / 3, b = n % 3;
if(b == 0) return (int)Math.pow(3, a);
if(b == 1) return (int)Math.pow(3, a - 1) * 4;
return (int)Math.pow(3, a) * 2;
}
}