MediumNo. 0343

Integer Break — LeetCode 343 Python Solution

Topics
Math, Dynamic Programming
Reading time
2 min

The problem

Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. Return the maximum product you can get.

Example

Input
n = 2
Output
1
Explanation
2 = 1 + 1, 1 × 1 = 1.

Python solution

PythonSolution
class Solution:
    def integerBreak(self, n: int) -> int:
        f = [1] * (n + 1)
        for i in range(2, n + 1):
            for j in range(1, i):
                f[i] = max(f[i], f[i - j] * j, (i - j) * j)
        return f[n]

Complexity

Time
O(n2)
Space · auxiliary
O(n)

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 343. Integer Break is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0062Unique PathsMedium
0070Climbing StairsEasy
0096Unique Binary Search TreesMedium
0233Number of Digit OneHard
0241Different Ways to Add ParenthesesMedium
0279Perfect SquaresMedium

Frequently asked questions

How hard is LeetCode 343. Integer Break?

LeetCode 343. Integer Break is rated Medium on LeetCode.

What is the time complexity of LeetCode 343. Integer Break?

The Python solution on this page runs in O(n2).

What is the space complexity of LeetCode 343. Integer Break?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 343. Integer Break cover?

LeetCode 343. Integer Break is tagged Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.