SDE & MLE Prep

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]