Title Description
You give a string of length n, please cut the rope segment length integer m (m, n are integers, n> 1 and m> 1), the length of each rope is referred to as k [0], k [1], ..., k [m]. Will k [0] xk [1] x ... xk [m] maximum possible product is how much? For example, when the length of the rope is 8:00, we cut it into lengths of three sections 2,3,3 of the product obtained at this time is the maximum 18.
Idea: cut the length of the rope as many 3 2 then built a little note that if left, then built 4 2 3 * 2 * 1 than good
public class Solution { public int cutRope(int target) { if(target <= 1) return 0; if(target == 2) return 1; if(target == 3) return 2; int x=target/3; int y=target%3; if(y == 1) { return 4*(int)Math.pow(3,x-1); } else if(y == 2){ return 2*(int)Math.pow(3,x); }else { return (int)Math.pow(3,x); } } }
Dynamic programming can also be
The length of the two halves is equal to the current product of the maximum length of each of the two half-product of the maximum - "optimal substructure and overlapping subproblems
public class Solution { public int cutRope(int target) { if(target <= 1) return 0; if(target == 2) return 1; if(target == 3) return 2; int[] project=new int[target+1]; project[0]=0; project[1]=1; project[2]=2; project[3]=3; for(int i = 4;i <= target;i ++){ int max=0; for(int j = 1;j <= i/2;j ++){ max=Math.max(max,project[j]*project[i-j]); } project[i] = max; } return project[target]; } }