343. Integer Break
Problem
Split the integer n into a sum of at least two positive integers and maximise their product. Return that product.
Example: 2 → 1; 10 → 36 (3 + 3 + 4)
Constraints: 2 ≤ n ≤ 58.
dp[i] = max over j of max(j, dp[j]) · (i − j). (Math shortcut: use as many 3s as possible, never a 1 — replace 3+1 with 2+2.)
Complexity: O(n²).
class Solution:
def integerBreak(self, n: int) -> int:
dp = [0, 1] + [0] * (n - 1)
for i in range(2, n + 1):
dp[i] = max(max(j, dp[j]) * (i - j) for j in range(1, i))
return dp[n]
assert Solution().integerBreak(2) == 1
assert Solution().integerBreak(10) == 36
class Solution {
public int integerBreak(int n) {
if (n <= 3) return n - 1;
int threes = n / 3, rem = n % 3;
if (rem == 1) { threes--; rem = 4; } // 3 + 1 -> 2 + 2
return (int) Math.pow(3, threes) * (rem == 0 ? 1 : rem);
}
}
func integerBreak(n int) int {
dp := make([]int, n+1) // dp[i] = best product splitting i into at least two parts
dp[1] = 1
for i := 2; i <= n; i++ {
for j := 1; j < i; j++ { // first part i-j; the rest j either kept whole or split further
dp[i] = max(dp[i], max(j, dp[j])*(i-j))
}
}
return dp[n]
}