#343
Integer Break
MediumMathDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution leverages the mathematical properties of numbers, specifically that breaking numbers into 2s and 3s yields the highest product. We can use dynamic programming to build up the maximum product for each integer up to n, using previously computed results.
⚙️
Algorithm
3 steps- 1Step 1: Create an array dp of size n+1 to store maximum products for each integer up to n.
- 2Step 2: Initialize dp[1] = 1 (not used but for consistency) and dp[2] = 1.
- 3Step 3: For each integer i from 3 to n, compute dp[i] as the maximum of dp[j] * (i - j) for j from 1 to i-1.
solution.py12 lines
1# Full working Python code
2
3def integer_break(n):
4 dp = [0] * (n + 1)
5 dp[1] = 1
6 for i in range(2, n + 1):
7 for j in range(1, i):
8 dp[i] = max(dp[i], j * (i - j), j * dp[i - j])
9 return dp[n]
10
11# Example usage
12print(integer_break(10)) # Output: 36ℹ
Complexity note: The time complexity is O(n²) due to the nested loops iterating through the integers, while the space complexity is O(n) because we store the maximum products in an array of size n.
- 1Breaking numbers into 2s and 3s generally yields the highest product.
- 2Dynamic programming can efficiently build solutions for larger problems based on smaller subproblems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.