Leetcode 343. Integer Break

博客围绕将正整数拆分为至少两个正整数并求其最大乘积的问题展开。指出将整数拆成尽量同样大小的数相乘结果较大,且拆分后乘积呈山峰状有极值。通过举例说明,只需找到乘积开始下降的点,就能得到最大值,并给出了解答思路。

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

题目:

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.

 

题意:

题意很简单,将一个正整数拆分(插分成两个以上的正整数,这些正整数相加的和为原来的数)后相乘,求相乘的最大值。

 

解答:

     首先,依照经验以及测试了几个数后可以判断

     1. 将整数拆成尽量同样大小的数相乘,结果会比较大

     2. 偶然发现,假设每次都尽量拆成同样的数,那么 拆分从小到大,乘积呈现一个山峰状,也就是存在一个极值,

例如对于10

1不考虑,2开始,2的五次方为32,之后3,3*3*4=36,之后4,4*4*2=32,之后5,5*5=25,之后6,6*4=24

32 36 32 25 24

我们可以看出这是一个山峰,所以我们只需要找到乘积在哪开始下降,就找到了最大点。

 

代码如下:

class Solution {
    public int integerBreak(int n) {
        if(n==2) return 1;
        int pre,now;
        pre=0;
        for(int i=2;i<n;i++){
            now = count(i,n);
            if(pre>now){
                break;
            }
            pre = now;
        }
        return pre;
    }
    public int count(int stub,int n){
        int times=n/stub;
        int l=n%stub;
        if(l==0) return (int)Math.pow(stub,times);
        else{
            if((l+stub)>l*stub&&times>1) return (int)Math.pow(stub,times-1)*(l+stub);
            else return (int)Math.pow(stub,times)*l;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值