整数拆分其积最大问题
$N = n_{1} + n_{2} + … + n_{k}$
若 $n_i\geq\ 5时,3 \times\ (n_i - 3) \geq\ n_i ,移项: 2 n_i \geq\ 9 $
$n_i = 4时,n_i = 2 + 2,其积:2 \times\ 2 $
最多两个2,原因:$2\times\ 2 \times\ 2 < 3 \times\ 3 $
说人话就是,将整数拆分为尽量多的3,最多2个2
题:25. 剪绳子
class Solution {
public:
int maxProductAfterCutting(int length) {
if (length <= 3) {
return 1 * (length - 1);
}
int ans = 1;
if (length % 3 == 1) {
ans = 2 * 2;
length -= 4;
} else if (length % 3 == 2) {
ans = 2, length -= 2;
}
int n = length / 3;
while (n--) {
ans *= 3;
}
return ans;
}
};
class Solution {
public:
int maxProductAfterCutting(int length) {
if (length <= 3) {
return 1 * (length - 1);
}
int ans = 1;
if (length % 3 == 1) {
ans = 2 * 2;
length -= 4;
} else if (length % 3 == 2) {
ans = 2, length -= 2;
}
while (length > 0) {
ans *= 3;
length -= 3;
}
return ans;
}
};