Integer Break
Problem
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.
Solution
public class Solution {
public int integerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
int res = 1;
while (n > 4) {
res *= 3;
n -= 3;
}
return res * n;
}
}
Analysis
The key idea of this problem is that we need to have as many 3
as possible in our product
This is because for any factor f >= 4
, we can divide by two numbers
And 2 * (f - 2) = 2f - 4
is always greater than f
as long as f >= 4
Hence we need to avoid any factor which is greater than 4
We update our result with 3
because 3 * 3
is better than 2 * 2 * 2
Simple as that