sagelearnai

Integer Break

Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #343

Break n (with n ≥ 2) into the sum of at least two positive integers so that their product is as large as possible. Return that product.

Examples

text
n = 2   →  1    (1 + 1)
n = 10  →  36   (3 + 3 + 4)

Hints

  1. DP: for the first piece j, the rest i − j is either kept whole or broken further.
  2. Math: pieces of size 3 are optimal. Never use 1s, and replace a 4 with 2 + 2 (same product).

Approach

DP: dp[i] = max over 1 ≤ j < i of max(j, dp[j]) × max(i − j, dp[i − j]). Taking max(x, dp[x]) handles "keep this piece whole or split it further". That's O(n²).

Math (O(1)): for n > 4, use as many 3s as possible. If the remainder is 1, turn one 3 + 1 into 2 + 2. Why 3? Splitting x ≥ 5 into 3 and x−3 gives 3(x−3) > x, and 3 beats 2 because 3² = 9 > 2³ = 8.

Complexity

Time: O(n²) for the DP, O(1) for the math. Space: O(n) for the DP.

Python solution
def integerBreak(n):
    dp = [0, 1] + [0] * (n - 1)
    for i in range(2, n + 1):
        for j in range(1, i):
            dp[i] = max(dp[i], max(j, dp[j]) * max(i - j, dp[i - j]))
    return dp[n]
JavaScript solution
function integerBreak(n) {
  if (n <= 3) return n - 1;
  const q = Math.floor(n / 3), r = n % 3;
  if (r === 0) return 3 ** q;
  if (r === 1) return 3 ** (q - 1) * 4;
  return 3 ** q * 2;
}