面试题14:剪绳子

1.算法源码

package com.offer;

import static java.lang.Math.pow;

/**
 * @authore Xavier
 * @description 面试题14:剪绳子
 * 题目:给你一根长度为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。
 * @date 2018/7/25
 */
public class CuttingRope {

    /**
     * 动态规划方式
     * 时间复杂度 O(n2)
     * 空间复杂度 O(n)
     *
     * @param length
     * @return
     */
    static int getMaxInDynamic(int length) {
        //必须要切一刀
        if (length < 2) {
            return 0;
        }
        if (length == 2) {
            return 1;
        }
        if (length == 3) {
            return 2;
        }

        //数组保存由底往上计算出的中间值
        int[] multipleVal = new int[length + 1];
        multipleVal[0] = 0;
        multipleVal[1] = 1;
        multipleVal[2] = 2;
        multipleVal[3] = 3;
        int max = 0;
        for (int i = 4; i <= length; i++) {
            for (int j = 1; j <= i / 2; j++) {
                int val = multipleVal[j] * multipleVal[i - j];
                if (max < val) {
                    max = val;
                }
            }
            multipleVal[i] = max;
        }
        max = multipleVal[length];
        return max;
    }

    //====================贪婪算法====================
    static int maxInGreey(int length) {
        if (length < 2) {
            return 0;
        }
        if (length == 2) {
            return 1;
        }
        if (length == 3) {
            return 2;
        }
        // 尽可能多地减去长度为3的绳子段
        int timesOf3 = length / 3;

        // 当绳子最后剩下的长度为4的时候,不能再剪去长度为3的绳子段。
        // 此时更好的方法是把绳子剪成长度为2的两段,因为2*2 > 3*1。
        if (length - timesOf3 * 3 == 1)
            timesOf3 -= 1;

        int timesOf2 = (length - timesOf3 * 3) / 2;

        return (int) (pow(3, timesOf3)) * (int) (pow(2, timesOf2));
    }
}

2.Test case

package com.offer;

import org.junit.Assert;
import org.junit.Test;

/**
 * @authore Xavier
 * @description
 * @date 2018/7/25
 */
public class CuttingRopeTest {
    @Test
    public void getMaxInDynamic() throws Exception {
        Assert.assertEquals(6, CuttingRope.getMaxInDynamic(5));
    }

    @Test
    public void getMaxInGreey() throws Exception {
        Assert.assertEquals(36, CuttingRope.maxInGreey(10));
    }

}

猜你喜欢

转载自blog.csdn.net/huaixiaozi90/article/details/81210352