原题链接在这里:https://leetcode.com/problems/integer-break/description/
题目:
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: You may assume that n is not less than 2 and not larger than 58.
题解:
若果n足够大,把n拆成小的数字. n 拆成 n/x 个 x, product 就是 x^(n/x). 目标就是使这个product 最大. 取derivative 得到 n * x^(n/x-2) * (1-ln(x)).
0<x<e 时derivative为正 product 增加. x>e时 derivative为负, product 减小. x=e时 derivative为零, product 最大.
最接近e的整数是2 和 3. 但尽量选3. 6 = 2+2+2 = 3+3. 2*2*2 < 3*3.
但4包括以下是特例. 4 = 1+3 = 2+2. 1*3 < 2*2.
所以4以上尽量减掉3, 4时直接乘以剩下的数.
Time Complexity: O(n). 每次减掉3, O(n/3)次.
Space: O(1).
AC Java:
1 class Solution { 2 public int integerBreak(int n) { 3 if(n == 2){ 4 return 1; 5 } 6 if(n == 3){ 7 return 2; 8 } 9 10 int res = 1; 11 while(n > 4){ 12 res *= 3; 13 n -= 3; 14 } 15 16 res *= n; 17 return res; 18 } 19 }