现需要将一根长为正整数 bamboo_len
的竹子砍为若干段,每段长度均为正整数。请返回每段竹子长度的最大乘积是多少。
示例 1:
输入: bamboo_len = 12 输出: 81
提示:
2 <= bamboo_len <= 58
注意:本题与主站 343 题相同:. - 力扣(LeetCode)
根据数学经验,绳子一定是各部分分成等分才可能乘出来值最大。
int cuttingBamboo(int bamboo_len) {int k = bamboo_len / 2;int max = k * (bamboo_len - k);int flag = 0;if (bamboo_len >= 6) {for (int i = 3; i <= bamboo_len / 2; i++) {k = (int)(bamboo_len/i);long long int p = k;for (int j = 0; j < i - 2; j++) {p *= k;}p *= bamboo_len - k * (i - 1);if (p > max)max = p;if (k * i == bamboo_len)continue;k = (bamboo_len/i)+1;p = k;for (int j = 0; j < i - 2; j++) {p *= k;}p *= bamboo_len - k * (i - 1);if (p > max)max = p;}}return max;
}
132:剪绳子二
现需要将一根长为正整数 bamboo_len
的竹子砍为若干段,每段长度均为 正整数。请返回每段竹子长度的 最大乘积 是多少。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:bamboo_len = 12 输出:81
提示:
2 <= bamboo_len <= 1000
注意:本题与主站 343 题相同:. - 力扣(LeetCode)
本人一直在写暴力解法
#include <stdio.h>
#include <limits.h>int cuttingBamboo(int bamboo_len) {int k = bamboo_len / 2;long long int max = k * (bamboo_len - k);int flag = 0;long long int max0 = 0;long long int max1 = 0;long long int MOD = 1000000007;if (bamboo_len >= 6) {for (int i = 3; i <= bamboo_len / 2; i++) {k = bamboo_len / i;long long int p = k;for (int j = 0; j < i - 2; j++) {if (p * k > MOD)flag = 1;p = (p * k) % MOD;}if (p * (bamboo_len - k * (i - 1)) > MOD)flag = 1;p = (p * (bamboo_len - k * (i - 1))) % MOD;if (p > max && flag == 0)max = p;if (p > max0 && flag == 1)max0 = p;if (k * i == bamboo_len)continue;k = bamboo_len / i + 1;p = k;for (int j = 0; j < i - 2; j++) {if (p * k > MOD)flag = 2;p = (p * k) % MOD;}if (p * (bamboo_len - k * (i - 1)) > MOD)flag = 2;p = (p * (bamboo_len - k * (i - 1))) % MOD;if (p > max && flag == 0)max = p;if (p > max1 && flag == 2)max1 = p;}}if (flag == 1)return max0;if (flag == 2) {if (max0 > max1)return max0;else return max1;}return max;
}
后来看见一个巧解,前2、3、4都可以直接算出结果
从5开始,经过数学推每次分为3结果最大。推导过程参考:LCR 131. 砍竹子 I - 力扣(LeetCode)
int cuttingBamboo(int bamboo_len) {if (bamboo_len == 2) {return 1;}if (bamboo_len == 3) {return 2;}if (bamboo_len == 4) {return 4;}long long res = 1;while (bamboo_len >= 5) {res = (res * 3) % 1000000007;bamboo_len -= 3;}res = (res * bamboo_len) % 1000000007;return res;
}