美文网首页
剑指 offer 学习之剪绳子

剑指 offer 学习之剪绳子

作者: Kevin_小飞象 | 来源:发表于2020-03-26 09:07 被阅读0次

题目描述

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

题目链接:力扣

解题思路

贪心
尽可能多剪长度为 3 的绳子,并且不允许有长度为 1 的绳子出现。如果出现了,就从已经切好长度为 3 的绳子中拿出一段与长度为 1 的绳子重新组合,把它们切成两段长度为 2 的绳子。

证明:当 n >= 5 时,3(n - 3) - n = 2n - 9 > 0,且 2(n - 2) - n = n - 4 > 0。因此在 n >= 5 的情况下,将绳子剪成一段为 2 或者 3,得到的乘积会更大。又因为 3(n - 3) - 2(n - 2) = n - 5 >= 0,所以剪成一段长度为 3 比长度为 2 得到的乘积更大。

public class Main {
    
    public static void main(String[] args) {
        System.out.println(integerBreak(8));
        System.out.println(integerBreak(10));
    }
    
    public static int integerBreak(int n) {
        if (n < 2) {
            return 0;
        }
        
        if (n == 2) {
            return 1;
        }
        
        if (n == 3) {
            return 2;
        }
        
        int timesOf3 = n / 3;
        if (n - timesOf3 * 3 == 1) {
            timesOf3--;
        }
        
        int timesOf2 = (n - timesOf3 * 3) / 2;
        return (int) (Math.pow(3, timesOf3)) * (int) (Math.pow(2, timesOf2));
    }
}

动态规划

public class Main {
    
    public static void main(String[] args) {
        System.out.println(integerBreak(8));
        System.out.println(integerBreak(10));
    }
    
    public static int integerBreak(int n) {
        int[] dp = new int[n + 1];
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j < i; j++) {
                dp[i] = Math.max(dp[i], Math.max(j * (i - j), dp[j] * (i - j)));
            }
        }
        return dp[n];
    }
}

测试结果

image.png

相关文章

网友评论

      本文标题:剑指 offer 学习之剪绳子

      本文链接:https://www.haomeiwen.com/subject/fvkxuhtx.html