给出一个整数n,将n分解为至少两个整数之和,使得这些整数的乘积最大化,输出能够获得的最大的乘积。
例如:
2=1+1,输出1;
10=3+3+4,输出36。
class MainActivity: def main(self): # Read the data n = int(input()) # Initialization maxProd = [1] # Traverse for num in range(1, n): realNum = num + 1 tmpResult = float('-inf') for subtractNum in range(1, realNum): subtractResult = realNum - subtractNum subtractResultIdx = subtractResult - 1 tmpResult = max(tmpResult, subtractNum * maxProd[subtractResultIdx], subtractNum * subtractResult) maxProd.append(tmpResult) print(maxProd[-1]) if __name__ == '__main__': M = MainActivity() M.main()
这个时间复杂度应该在O(n²)的样子,AC运行时间是45ms。
class MainActivity: def main(self): # Read the data n = int(input()) # Initialization result = float('-inf') # Traverse for k in range(1, n + 1): if n % k: lowNum = n // k highNum = lowNum + 1 result = max(result, lowNum ** (k * lowNum + k - n) * highNum ** (n - k * lowNum)) else: result = max(result, (n // k) ** k) print(result) if __name__ == '__main__': M = MainActivity() M.main()遍历的时间复杂度是O(n),但我感觉乘方也挺耗时间的,看乘方做快速幂优化才行吧。