#3857
Minimum Cost to Split into Ones
MediumMathDynamic ProgrammingDynamic ProgrammingRecursion
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)
Using dynamic programming, we can build solutions for smaller integers up to n, storing the minimum costs to avoid redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array dp where dp[i] represents the minimum cost to split integer i.
- 2Step 2: For each integer i from 2 to n, calculate the minimum cost by trying all splits j from 1 to i-1.
- 3Step 3: Update dp[i] with the minimum value found for all splits.
solution.py7 lines
1def minCost(n):
2 dp = [0] * (n + 1)
3 for i in range(2, n + 1):
4 dp[i] = float('inf')
5 for j in range(1, i):
6 dp[i] = min(dp[i], j * (i - j) + dp[j] + dp[i - j])
7 return dp[n]ℹ
Complexity note: We compute results for each integer up to n, storing them, leading to O(n²) time and O(n) space.
- 1Always split into 1 and n-1 for minimal cost.
- 2Dynamic programming avoids redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.