题目
给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]…k[m] 。请问 k[0]k[1]…*k[m] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
1
2
3 输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1示例 2:
1
2
3 输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36提示:
2 <= n <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这道题乍一看跟上一道题一模一样,看了题解才知道是考察大数运算,这里是大数求余。
大数求余解法:
- 为什么需要大数求余?
当计算结果超出变量类型可表示的范围时会导致结果错误 - 解法
循环求余、快速幂求余,其中后者的时间复杂度更低
实现
贪心算法
由于可以证明:将一根绳子剪成 m 段,使乘积最大的方案是每段绳子长度为 3,最短为 2。
因此可以使用贪心算法,每一步取 3。但是有一种情况:变量在乘以 3 之前小于取余阈值,而乘 3 之后大于整形可表示范围。在这种情况下,循环求余会出错(溢出)。
上述错误仅仅会发生在使用 int 存储变量的情况下,而使用 long 则不会发生溢出,因为$3\times (1e9+7) < 2^{63}-1$。