問題
例子
思路
跟剪繩子1不一樣的是,n的範圍變大,剪繩子1中n<=58,此時結果<Integer.MAX_VALUE,
此題:n<=1000,所以中間結果會出現>int的最大值,和大於long的最大值,只能使用BigInteger,比較麻煩
所以:採用貪心算法
可以看到當n>=5時,最大結果總是先割下來長度3,不夠5, 直接保留【因爲4的最大結果爲4(22),3的最大爲3(max(3,12)),2的最大爲2 (max(2, 1*1) )】
-
方法1
$$$$
-
方法2
$$$$
代碼
//方法1
class Solution {
public int cuttingRope(int n) {
if(n==2) return 1;
if(n==3) return 2;
//10^9*3>Integer.MAX_VALUE && 10^9<1000000007
long res = 1;
while(n>=5) {
res = res*3%1000000007;
n-=3;
}
//n出循環時,爲4,3,2,
res = (res*n)%1000000007;
return (int)res;
}
}
//方法2