#3864
Minimum Cost to Partition a Binary String
HardStringDivide and ConquerPrefix SumDynamic 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 a recursive approach with memoization, we can efficiently calculate the minimum cost by evaluating segments and considering splits only when the length is even.
⚙️
Algorithm
3 steps- 1Step 1: Use a recursive function to calculate the cost of a segment.
- 2Step 2: If the segment's length is even, compute the cost for both halves and take the minimum.
- 3Step 3: Store results in a memoization table to avoid redundant calculations.
solution.py15 lines
1def minCost(s, encCost, flatCost):
2 memo = {}
3 def dfs(start, end):
4 if (start, end) in memo: return memo[(start, end)]
5 segment = s[start:end]
6 X = segment.count('1')
7 L = len(segment)
8 cost_no_split = flatCost if X == 0 else L * X * encCost
9 min_cost = cost_no_split
10 if (end - start) % 2 == 0:
11 mid = (start + end) // 2
12 min_cost = min(min_cost, dfs(start, mid) + dfs(mid, end))
13 memo[(start, end)] = min_cost
14 return min_cost
15 return dfs(0, len(s))ℹ
Complexity note: The complexity is linear due to memoization, which avoids redundant calculations for segments.
- 1Recursive partitioning minimizes costs effectively.
- 2Memoization avoids redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.