剑指 Offer 14- I. 剪绳子

给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m-1] 。请问 k[0]k[1]...*k[m-1] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jian-sheng-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {

    // 均值不等式求出乘积最大值 L(m)=(n/m)^m, m=n/e 最大
    public int cuttingRope(int n) {
        if (n <= 3) {
            return n - 1;
        }
        int three = n / 3;
        int other = n % 3;
        if (other == 0) {
            return (int) Math.pow(3, three);
        } else if (other == 1) {
            return (int) Math.pow(3, three - 1) * 4;
        } else {
            return (int) Math.pow(3, three) * 2;
        }
    }
}
posted @ 2022-01-17 23:12  Tianyiya  阅读(27)  评论(0)    收藏  举报