[WXM] LeetCode 343. Integer Break C++

博客围绕LeetCode 343题“整数拆分”展开,给定正整数n,需将其拆分为至少两个正整数之和并使乘积最大。作者采用递推方法解决该问题,还提及类似用递推法的LeetCode 416题。

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

343. 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.

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.
  • Note: You may assume that n is not less than 2 and not larger than 58.

Approach

  1. 题目大意给你一个数,问你某些数字合等于它并且它们的乘积最大是多少,看到这道题,如果之前有做个几个递推类的题目,那么这道题也就很容易就想到用递推来解决,然后这里我也还是用递推来解,我们设dp[i],当数等于i,它的最大乘机就为dp[i],所以就能想出递推公式dp[i]=max(dp[i],dp[i-j]*j),j<=i,边界dp[0]=1,因为每个数都要被减到零才能算出最大的乘机,但是又不能直接相乘零,所以只能设dp[0]=1,不过题目有说n>=2,就算没有,对n==0做特殊判断就好。
  2. [WXM] LeetCode 416. Partition Equal Subset Sum C++以上的题也是用到递推的方法。

Code

class Solution {
public:
    int integerBreak(int n) {
        int c;
        if (n % 2)c = n / 2 + 1;
        else c = n / 2;
        vector<int>dp(n + 1, 0);
        dp[0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= c&&i >= j; j++) {
                dp[i] = max(dp[i], dp[i - j] * j);
            }
        }
        return dp[n];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值