Problem 343

Abstract / Summary

Break a number into parts to maximize the product of those parts without using the number itself.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0343.py

class Solution:
    def integerBreak(self, n: int) -> int:
        best = 0
        for k in range(2, n+1):
            x = n // k
            remainder = n % k

            product = 1
            for i in range(k):
                if remainder > 0:
                    product *= x + 1
                    remainder -= 1
                else:
                    product *= x

            best = max(best, product)

        return best
18 lines | 456 bytes | submitted August 20, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 63% (700k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the integer-break problem by enumerating every possible count of summands (k) and computing the maximal product that can be obtained when the original integer n is split into exactly k positive parts. For each k the algorithm determines the most balanced distribution of the parts-values differ by at most one-because such a distribution yields the greatest product for a fixed number of terms. The best product across all k values is retained and returned.

Core Logic

Enumerating the number of parts

for k in range(2, n+1):

The outer loop iterates from two parts up to n parts. The lower bound of two guarantees that the integer is actually broken, while the upper bound includes the degenerate case where every part equals one.

Determining the base size of each part

x = n // k
remainder = n % k

x is the integer quotient of n divided by k. It represents the size of the majority of the parts. remainder counts how many parts must be incremented by one to account for the leftover value after the even division.

Building the product without auxiliary containers

product = 1
for i in range(k):
    if remainder > 0:
        product *= x + 1
        remainder -= 1
    else:
        product *= x

A single accumulator product is multiplied by each part as it is generated. The conditional adds one to the part while there are still leftovers (remainder > 0). This approach avoids constructing a list of parts, thereby keeping memory usage minimal and the inner loop tight.

Updating the optimal result

best = max(best, product)

After the product for the current k is computed, it is compared with the best product seen so far. The larger value becomes the new best.

Returning the final answer

return best

When all possible k values have been examined, the function returns the maximum product found.

Edge Cases Handled

When n is the smallest permissible value (typically 2), the outer loop runs only for k = 2. The division yields x = 1 and remainder = 0, so the inner loop multiplies product by 1 twice, resulting in 1. This matches the expected outcome for the integer-break problem, where the integer must be split into at least two positive integers.

If n is a prime number, the algorithm still evaluates every k. The distribution logic ensures that the parts are as equal as possible, even when an even split is impossible. The remainder handling guarantees that the extra units are spread across the first few parts, preserving the property that the difference between any two parts never exceeds one.

When n equals k, the division yields x = 1 and remainder = 0. The inner loop multiplies product by 1 exactly k times, producing a product of 1. This case is naturally covered without special-case code.

Performance Optimizations Observed

The implementation relies exclusively on integer arithmetic and a small, fixed set of variables. By computing the product directly inside the inner loop, it eliminates the need for temporary arrays or list comprehensions, which reduces both allocation overhead and garbage-collection pressure.

The use of n // k and n % k provides the quotient and remainder in a single step each, avoiding repeated division operations inside the inner loop. This keeps the inner loop’s body lightweight: a single multiplication and a conditional decrement of remainder.

Because the algorithm updates best only after a complete product for a given k is available, it avoids unnecessary intermediate comparisons, further streamlining the execution path.

Overall, the code balances clarity with efficient use of primitive operations, delivering a solution that is both easy to follow and performant for the problem’s typical input range.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having a big pile of building blocks that you want to split into smaller groups so the numbers inside those groups multiply together to make the biggest crowd possible. This code is like a clever helper that picks up the pile and tries out every possible way to break it into different chunks. It starts by testing what happens if you break the pile into two groups, then it tries three groups, and keeps going until it reaches as many groups as blocks available.

Inside the loop, the code does some math to make sure the blocks are spread out as evenly as possible. It takes the total number of blocks and shares them out among the groups. If there are a few leftovers, it passes them out one by one to make some of the groups slightly larger than the others because that makes the final result even bigger.

Once the groups are set, it multiplies all those numbers together to see how huge the total is. Every time it finishes making a set of groups, it compares the new total to the best one found so far. If the new one is bigger, it remembers that as the new champion. After trying all the different ways to break up the pile, the code holds onto the largest number found at the very end.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.85 | σ = 1.46

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java Rust Go C# C TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
halfrost Go
haoel C++
JoshCrozier JS
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
halfrost Go
haoel C++
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
zfang399 C++
41 links | 23 authors | 9 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 easy 1 medium
5 solutions   August 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality