Leetcode problem 343 reads as follows:
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.
To solve this problem, notice:
n
into at least two positive integers.The key observation is that products of smaller integers like 2 and particularly 3 (due to Euler’s and other mathematical proofs) tend to yield higher products. More formally:
n <= 3
, then the result is simply n - 1
because:
n = 2
, we can only break it into 1 + 1
.n = 3
, we can only break it into 1 + 2
.n >= 4
, breaking n
into factors of 3 as much as possible maximizes the product:
n
modulo 3 equals 1, then use one 4 (e.g. n = 10 -> 3 + 3 + 4
).n
modulo 3 equals 2, use one 2 (e.g. n = 8 -> 3 + 3 + 2
).n = 9 -> 3 + 3 + 3
).def integerBreak(n: int) -> int:
# Handle base cases
if n <= 3:
return n - 1
# Initialize product
product = 1
# Use as many 3's as possible
while n > 4:
product *= 3
n -= 3
# Multiplying the remainder n directly to product
return product * n
# Example usage:
print(integerBreak(2)) # Output: 1
print(integerBreak(10)) # Output: 36
The time complexity of the above algorithm is O(1) (constant time), because the while loop iterates at most n / 3
times, but in practical sense, the operations are minimal and do not depend on input size proportionally. Therefore, it is very efficient. The space complexity is also O(1) as no extra space besides the variables to hold the product and the remainder is used.
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?