1

Integer Break

Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

Note: you may assume that n is not less than 2.

Hint:

There is a simple O(n) solution to this problem.
You may check the breaking results of n ranging from 7 to 10 to discover the regularities.

DP

复杂度

O(N) 时间 O(N) 空间

思路

dp[i]表示i这个数字拆分后的最大乘积,最后的答案是dp[n].
初始化:
dp[0] = 0 //这个无所谓
dp[1] = 1 //得是1,方便后面乘法
dp[2] = 1,
dp[i] = Max(dp[k] * dp[i - k], k * (i - k), dp[k] * (i - k), k * (dp[i - k])), k取值从[1, i / 2]闭区间

看图说话:
图片描述

注意

注意对于一个拆分有四种情况,不是两种!

代码

public int integerBreak(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 0;//用不着,随便设
        dp[1] = 1;
        dp[2] = 1;
        for (int i = 3; i <= n; i++) {
            int max = Integer.MIN_VALUE;
            for (int k = 1; k <= i / 2; k++) {
                int tmpMax = Math.max(dp[k] * dp[i - k], k * (i - k));
                tmpMax = Math.max(tmpMax, dp[k] * (i - k));
                tmpMax = Math.max(tmpMax, dp[i - k] * k);
                max = Math.max(tmpMax, max);
            }
            dp[i] = max;
        }
        return dp[n];
    }

liuqi627
364 声望100 粉丝

引用和评论

0 条评论