Leetcode | Integer Break

探讨如何将一个整数拆分成至少两个正整数之和,使得这些数的乘积最大化。给出了一种高效算法,仅需O(n)的时间复杂度。

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

原题链接:https://leetcode.com/problems/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 and not larger than 58.

题目大概意思就是给定一个整数n,然后把它分解成至少2个数的和,然后这些分解后的数字的积要达到最大,最后输出这个最大积。

这道题刚着手去想时,会觉得有点复杂,因为把它分解成至少两个数的情况太多了,根本就不可能全部列举出来,但仔细思考后会发现,只要把它分解成2或者3这些数的和,它们的积就会达到最大值,所以这道题就变得很简单了,只需要O(n)就能解决。


以下为源代码:

class Solution {
public:
    int integerBreak(int n) {
         if(n==2) return 1;
        if(n==3) return 2;
        int product = 1;
        while(n>4){
            product*=3;
            n-=3;
        }
        product*=n;

        return product;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值