剑指 Offer14-Ⅱ 剪绳子Ⅱ【快速幂、数学】

题目描述

给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]…k[m - 1] 。请问 k[0]k[1]…*k[m - 1] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。

答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。

示例 1:

输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1

示例 2:

输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36

提示:

  • 2 <= n <= 1000

解题思路

基本思路同14-Ⅰ剪绳子是一样的,通过数学公式求导推理可以得出,在分段的过程中,尽可能让每段都为3的情况下,乘积是最大的。

由于此题的N较大,会出现大数情况,所以对求解3的times次方采用快速幂的方式进行求解。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
static class Solution14_2 {
public int cuttingRope(int n) {
if(n<=3){
return n-1;
}
long res=1;
long x=3;
int times=n/3;
if(n-times*3==1){//当分完数为3的times段后,还剩1时,会发现 1 3的乘积小于2 2的乘积,所以此情况需要减少一次分为3的段。
times--;
}
int mod=(n-times*3)/2;
while(times!=0){//快速幂
res=(times&1)==1?(res*x)%1000000007:res;
times/=2;
x=x*x%1000000007;
}
return (int)(res*Math.pow(2,mod)%1000000007);
}
}

复杂度分析

时间复杂度:O(log2t) t为times

空间复杂度:O(1)

资源

https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof

剑指 Offer14-Ⅱ 剪绳子Ⅱ【快速幂、数学】

http://example.com/2021/04/11/14-Ⅱ-剪绳子Ⅱ/

Author

John Doe

Posted on

2021-04-11

Updated on

2021-06-08

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.