Idea: This
question is a mathematical proof question. Of course, it is easy to figure it out. If you do it with greedy thinking, we can know this inference: When the rope is divided into multiple sections with a length of 3 as much as possible, the product is the largest. Then if there is a remainder, if it is 2, there is no need to split, if it is 1, then a 3 plus this 1 must be split into 2+2.
Click here for specific proof!
Code:
class Solution {
public:
int cuttingRope(int n) {
if(n==2) return 1;
if(n==3) return 2;
int sum_3 = n / 3;
int mod = n%3;
int sum_2 = 0;
if(mod==1){
sum_3-=1;
sum_2+=2;
}else if(mod==2){
sum_2+=1;
}
int sum = 1;
while(sum_3--){
sum*=3;
}
while(sum_2--){
sum*=2;
}
return sum;
}
};
Idea: There is
no difference between this question and the previous question. It mainly uses fast exponentiation and fast product templates.
class Solution {
public:
int cuttingRope(int n) {
if(n==2) return 1;
if(n==3) return 2;
int sum_3 = n / 3;
int mod = n%3;
int sum_2 = 0;
if(mod==1){
sum_3-=1;
sum_2+=2;
}else if(mod==2){
sum_2+=1;
}
int sum = 1;
func_mi(sum,3,sum_3);
int SUM = 1;
func_mi(SUM,2,sum_2);
return func_MUL(sum,SUM);
}
void func_mi(int& sum,int bk,int len){
while(len){
if(len&1) sum = func_MUL(sum,bk); //sum = sum*bk;
bk = func_MUL(bk,bk);
//bk<<=1;
len>>=1;
}
return ;
}
int func_MUL(int a,int b){
int sum = 0;
while(b){
if(b&1) sum = (sum+a)%MOD;
a = (a+a)%MOD;
b >>= 1;
}
return sum%MOD;
}
private:
int MOD = 1e9+7;
};