Given an integer n
, break it into the sum of k
positive integers, where k >= 2
, and maximize the product of those integers.
Return the maximum product you can get.
Example 1:
Input: n = 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: n = 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Constraints:
2 <= n <= 58
The problem asks to find the maximum product obtained by breaking a given integer n
into a sum of at least two positive integers.
This approach uses dynamic programming to build up a solution iteratively.
1. State Definition:
Let f[i]
represent the maximum product achievable by breaking the integer i
. f[1] = 1
(base case: no break possible).
2. State Transition:
For each integer i
, we consider all possible ways to split it into two parts j
and i-j
where 1 <= j < i
. The maximum product for i
is the maximum of:
f[i-j] * j
: The product obtained by breaking i-j
optimally and multiplying by j
.(i-j) * j
: The product obtained without further breaking i-j
.Thus, the recurrence relation is:
f[i] = max(f[i], max(f[i-j] * j, (i-j) * j)) for all j in [1, i-1]
3. Base Case:
f[1] = 1
4. Algorithm:
Iterate from i = 2
to n
, applying the recurrence relation to compute f[i]
. The final result is f[n]
.
Time Complexity: O(n^2) due to the nested loops.
Space Complexity: O(n) to store the f
array.
This approach leverages mathematical insights to derive a more efficient solution.
1. Observation:
For n >= 4
, repeatedly dividing by 3 gives the best result because 3 * 3 > 2 * 2 * 2 and 2 * 3 > 1 * 1 * 1 * 1.
2. Algorithm:
n < 4
, return n - 1
.n
by 3 until the remainder is 0, 1, or 2.Time Complexity: O(log n) due to repeated division by 3 (or O(1) if considering the number of divisions as constant). Space Complexity: O(1).
Approach 1 (Dynamic Programming):
def integerBreakDP(n):
f = [1] * (n + 1)
for i in range(2, n + 1):
for j in range(1, i):
f[i] = max(f[i], f[i - j] * j, (i - j) * j)
return f[n]
Approach 2 (Mathematical Optimization):
def integerBreakMath(n):
if n < 4:
return n - 1
if n % 3 == 0:
return 3**(n // 3)
if n % 3 == 1:
return 4 * 3**((n - 4) // 3)
return 2 * 3**(n // 3)
Both approaches are included in the detailed markdown response above, in multiple programming languages. The mathematical approach is significantly faster for larger values of n
.