◀ THE GRIND — 1-D DYNAMIC PROGRAMMING

Integer Break

MEDIUM✓ CHIP-TIMEDLC #343 — FULL STATEMENT ↗

The drill: Split a whole number n into two or more positive integers that add back up to n, and maximize the product of those parts — pick the split that multiplies out the biggest.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A whole number n arrives, and the task is to break it into two or more positive integer pieces that add back up to n, choosing the split that makes the pieces' product as large as possible.

At least two pieces are required — leaving n unbroken is not a valid answer, even if breaking it would lower the product. Any number of pieces beyond two is allowed, and pieces can repeat in value.

The output is the single largest product achievable across every possible way of splitting n this way.

EX 01
n = 2
1
MINIMUM SIZE, FORCED 1 + 1
EX 02
n = 4
4
2 + 2 BEATS 3 + 1
EX 03
n = 5
6
2 + 3
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

The last cut you make turns a size-i problem into: some piece k, times whatever is best for the rest — either left whole or broken again. What recurrence captures 'broken again, or not'?

HINT 2 THE STRUCTURE

best(i) = the max over every first piece k < i of max(k · (i − k), k · best(i − k)) — the (i − k) itself is a candidate too, since it might be better left unbroken.

HINT 3 ONE STEP FROM THE ANSWER

That table is correct but there's a closed form hiding in it: the product is maximized by cutting into as many 3s as possible, trading a lone leftover 1 for a 4, or keeping a leftover 2 as-is.

COACH'S BOARD — THE PATTERN, STEP BY STEP
GREEDY THREESPATTERN · GREEDY THREESn = 11
3
3
3
2
RUNNING PRODUCT
— empty —
STEP 1

11 breaks into as many 3s as possible: 11 = 3 + 3 + 3 + 2 — the leftover 2 stays whole since splitting it further only shrinks the product.

STEP 1 / 6 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/integer-break.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def integerBreak(self, n: int) -> int:
        if n == 2:
            return 1
        if n == 3:
            return 2
        quotient, remainder = divmod(n, 3)
        if remainder == 0:
            return 3 ** quotient
        if remainder == 1:
            # a lone leftover 1 is wasted — trade a 3 for a 4 instead (3*1 < 4)
            return 3 ** (quotient - 1) * 4
        return 3 ** quotient * 2
TIME O(LOG N)SPACE O(1)PYTHON · RACE PACE · 13 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED