Integer Break Problem
Description
LeetCode Problem 343.
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
Solution
Approach: Use as Many 3s as Possible
A DP over all split points works in O(n2), but a short argument gives the answer directly.
Look at which part sizes can appear in a best split:
- A part
p >= 5should be split again:3 * (p - 3) = 3p - 9 > pwhenp >= 5, so replacingpwith3andp - 3raises the product. - A part
4can stay or become2 + 2; the product is the same. - A part
1is wasted: adding it to any other part increases the product. - Three 2s should become two 3s, since
2 * 2 * 2 = 8 < 9 = 3 * 3.
So a best split uses only 3s, plus at most two 2s (or one 4). That gives a simple loop: while more than 4 is left, take a 3. What remains is 2, 3 or 4, and it is the last part. For n = 10: take 3, take 3, and 4 is left, giving 3 * 3 * 4 = 36.
The case people miss is small n. We must split into at least two parts, so n = 2 gives 1 * 1 = 1 and n = 3 gives 1 * 2 = 2, both smaller than n itself. The loop above would return n for them, so they are handled first.
For n = 58 the answer is 318 · 4 = 1549681956, which still fits in a 32-bit integer.
Complexity: O(n) time (the loop runs about n / 3 times) and O(1) space.
class Solution:
def integerBreak(self, n: int) -> int:
if n <= 3:
return n - 1 # must split into at least two parts: 2 = 1 + 1, 3 = 1 + 2
product = 1
while n > 4:
product *= 3 # take a 3 while what is left stays at least 2
n -= 3
return product * n # the last part is 2, 3 or 4
Now write it from memory
Close the write-up and solve it yourself against the tests.