leetcode 剑指Offer 14-I.剪绳子 Java

做题博客链接

https://blog.csdn.net/qq_43349112/article/details/108542248

题目链接

https://leetcode-cn.com/problems/jian-sheng-zi-lcof/

描述

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



提示:
2 <= n <= 58

示例

示例 1:

输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1

示例 2:

输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36

初始代码模板

class Solution {
    
    
    public int cuttingRope(int n) {
    
    

    }
}

代码

数学推导请看下面的题解:
https://leetcode-cn.com/problems/jian-sheng-zi-lcof/solution/mian-shi-ti-14-i-jian-sheng-zi-tan-xin-si-xiang-by/

class Solution {
    
    
    public int cuttingRope(int n) {
    
    
        if (n <= 3) {
    
    
            return n - 1;
        }
        int threeNum = n / 3;
        n %= 3;

        if (n == 0) {
    
    
            return (int)Math.pow(3, threeNum);
        } else if (n == 1) {
    
    
            return (int)Math.pow(3, threeNum - 1) * 4;
        } else {
    
    
            return (int)Math.pow(3, threeNum) * 2;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43349112/article/details/113747772