给你一根长度为 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。其中,2 <= n <= 58
Solution 1
1
2
3
4
5
6
7
8
9
10
11
classSolution:# Dynamic ProgrammingdefcuttingRope(self,n:int)->int:dp=[0]*(n+1)dp[2]=1# 2 = 1 + 1; res = 1 * 1 = 1foriinrange(3,n+1):forjinrange(2,i):# Starting from 2 because 1 doesn't change the result in multiplicationdp[i]=max(dp[i],j*(i-j),j*dp[i-j])# 1) Keep unchanged# 2) Cut length of j and keep the rest line unchanged# 3) Cut length of j and continue to cut following the way of dp[i-j]returndp[n]
classSolution:'''
1) The length of each sub-line should be as equal as possible.
2) The optimal length of each sub-line is 3.
'''defcuttingRope(self,n:int)->int:ifn<4:returnn-1a,b=n//3,n%3ifb==0:returnpow(3,a)elifb==1:# The last length is 1. Instead, we deal with the last two sub-lines, because 2*2 > 3*1returnpow(3,a-1)*4else:# b == 2returnpow(3,a)*2
Explanation
Solution 1
Time Complexity: O(N2)
Space Complexity: O(N)
Solution 2
Time Complexity: O(N)
Space Complexity: O(1)
Solution 3
Time Complexity: O(1)
Space Complexity: O(1)
Assuming we have a line with length n, we want to cut it evenly into m pieces with the length of x.
The product x∗xnreaching maximum happens when x∗x1 is the maximum.
Therefore, we need to find the integer x so that xx1 is the largest.
Apply log to the equation, y=xx1→ln(y)=ln(xx1)
Calculate the derivative of y in respect to x: ∂x∂y=x21−lnxxx1=0
When x0=e, it reaches maximum. Because x is an integer, x=3 is the best solution.
classSolution:# Sliding WindowdeffindContinuousSequence(self,target:int)->List[List[int]]:i,j=1,2total,res=i+j,[]whilej-i>0:iftotal==target:res.append(list(range(i,j+1)))iftotal>=target:# We need to remove the first numtotal-=ii+=1else:# We need to add the next numj+=1total+=jreturnres