AcWing打卡活动
《剑指Offer》打卡活动
周二第二题 剪绳子
/**
* 1、设 ni >= 5, 3 * (ni - 3) >= ni? 2 * ni >= 9? 衡大于
* 2、ni = 4 时, 拆分为2 * 2 才为最大
* 3、2 * 2 * 2 < 3 * 3 故能拆分成3时,尽量拆分为三
* 4、除了边界情况不得已才会拆分出1
* 5、最大值为58, 59会溢出 -1970444362
*/
class Solution {
public int maxProductAfterCutting(int length)
{
// 边界判断 当 2 <= length <= 3时,因为必须要拆除了一段
if(length <= 3) return 1 * (length - 1);
int res = 1;
// 如果求余后,为4 ,则 为 2 * 2 的情况,成积为4
if(length % 3 == 1) {
res *= 4;
length -= 4;
} else if (length % 3 == 2) { // 如果秋雨后为2,则可以减去一个二
res *= 2;
length -= 2;
}
// 以上的if判断完成后,接下来都是3的倍数了,n个3相乘可确保最大
while(length > 0) {
res *= 3;
length -= 3;
}
return res;
}
}