LeetCode 343. Integer Break

文章讨论了LeetCode第343题《IntegerBreak》的解法,主要涉及动态规划和数学策略。对于给定的整数n,目标是将其分解为至少两个正整数的和,并最大化这些整数的乘积。动态规划解决方案通过dp[i]表示i的最大乘积,而数学方法则建议当n大于等于5时优先分解为3,当n等于4时分解为2*2。文章提供了两种不同的代码实现,分别使用了动态规划和简化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 343. Integer Break

题目

Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

Return the maximum product you can get.

翻译

给定一个整数n,将其分解为k个正整数的和,其中k>=2,并最大化这些整数的乘积。
返回你可以得到的最大乘积。

样例

Example 1:

Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.

Example 2:

Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

思路

思路1

动态规划,dp[i]表示i的最大乘积,dp[i] = max(dp[i], max(j, dp[j]) * max(i-j, dp[i-j])),其中j为1到i-1的数。

思路2

数学方法,当n>=5时,尽可能多的分解为3,当n=4时,分解为2*2。

代码

代码1

class Solution {
    public 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, dp[j]) * Math.max(i - j, dp[i - j]));
            }
        }
        return dp[n];
    }
}

代码2

class Solution {
    public int integerBreak(int n) {
        if (n == 2) {
            return 1;
        }
        if (n == 3) {
            return 2;
        }
        int res = 1;
        while (n > 4) {
            res *= 3;
            n -= 3;
        }
        return res * n;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值