LeetCode Integer Break

本文解析了LeetCode上的一道经典题目——整数拆分问题,旨在通过数学推导找到将一个正整数拆分成至少两个正整数之和时,使得这些整数的乘积最大的方法。文章给出了一个高效的算法实现,并通过实例说明了解决方案的有效性。

原题链接在这里:https://leetcode.com/problems/integer-break/description/

题目:

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足够大,把n拆成小的数字. n 拆成 n/x 个 x, product 就是 x^(n/x). 目标就是使这个product 最大. 取derivative 得到 n * x^(n/x-2) * (1-ln(x)).

0<x<e 时derivative为正 product 增加. x>e时 derivative为负, product 减小. x=e时 derivative为零, product 最大.

最接近e的整数是2 和 3. 但尽量选3. 6 = 2+2+2 = 3+3. 2*2*2 < 3*3.

但4包括以下是特例. 4 = 1+3 = 2+2. 1*3 < 2*2.

所以4以上尽量减掉3, 4时直接乘以剩下的数.

Time Complexity: O(n). 每次减掉3, O(n/3)次.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int integerBreak(int n) {
 3         if(n == 2){
 4             return 1;
 5         }
 6         if(n == 3){
 7             return 2;
 8         }
 9         
10         int res = 1;
11         while(n > 4){
12             res *= 3;
13             n -= 3;
14         }
15         
16         res *= n;
17         return res;
18     }
19 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/7596703.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值