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 obtain.
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
n
be 1?
n
starts from 2 as per constraints.n
(like 2 and 3) where the breakdown is straightforward.To break down the integer n
into parts that yield the maximum product, we can use mathematical insights:
n % 3 == 0
, it’s optimal to break entirely into 3’s.n % 3 == 1
, it’s optimal to use one 2 and then continue with 3’s.n % 3 == 2
, simply use the extra 2 along with the 3’s.public class Solution {
public int integerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
int product = 1;
while (n > 4) {
product *= 3;
n -= 3;
}
// when n is less than or equal to 4, it can only be 2, 3 or 4
// and it is optimal to just multiply the remaining value
return product * n;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test cases
System.out.println(sol.integerBreak(2)); // Output: 1
System.out.println(sol.integerBreak(10)); // Output: 36
System.out.println(sol.integerBreak(5)); // Output: 6
System.out.println(sol.integerBreak(6)); // Output: 9
}
}
n
is greater than 4.n == 2
, the only way to split is (1+1). Hence, the product is (1\times1=1).n == 3
, the only way to split is (2+1). Hence, the product is (2\times1=2).n
values:
n
repeatedly (maximizing product by using as many 3’s as possible).n
is less than or equal to 4, we multiply it with our product.This mathematical insight ensures we maximize the product with the most efficient breakdowns.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?