Integer Break — LeetCode 343 Python Solution
- Problem
- #343
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n) auxiliary |
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
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(n^2).
- 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.