题解 | #剪绳子#贪心解决
剪绳子
https://www.nowcoder.com/practice/57d85990ba5b440ab888fc72b0751bf8
思路:均分一条绳子的时候乘积最大,证明如其他题解所示。
解法:1. int len_short = n / i; n长绳子均分为i段,每段最小长度;
2. int len_long_num = n % i; 求解多余长度分发到其他段+1 长度的数量;
3. tmp *= ((len_long_num-- > 0) ? (len_short + 1) : len_short); 循环求解当前均分情况最大面积;
代码如下:
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return int整型
*/
int cutRope(int n) {
// write code here
int max_num = 0;
for (int i = n; i > 1; --i) {
int len_short = n / i;
int len_long_num = n % i;
int tmp = 1;
for (int j = 0; j < i; ++j) {
tmp *= ((len_long_num-- > 0) ? (len_short + 1) : len_short);
}
if (tmp > max_num) max_num = tmp;
}
return max_num;
}
};

查看10道真题和解析