#3219
Minimum Cost for Cutting Cake II
HardArrayGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m log m + n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(m log m + n log n)Space O(1)
The optimal solution uses a greedy approach, where we always cut along the line with the highest cost. This is because the cost of cutting increases with the number of pieces created; thus, we want to maximize the cost of each cut by cutting the most expensive lines first.
⚙️
Algorithm
4 steps- 1Step 1: Sort the horizontalCut and verticalCut arrays in descending order.
- 2Step 2: Initialize total cost to 0, and set initial horizontal and vertical piece counts to 1.
- 3Step 3: Use two pointers to iterate through both sorted arrays, choosing the higher cost cut at each step.
- 4Step 4: For each cut, update the total cost based on the number of pieces created and increment the respective piece count.
solution.py26 lines
1# Full working Python code
2def minCostOptimal(m, n, horizontalCut, verticalCut):
3 horizontalCut.sort(reverse=True)
4 verticalCut.sort(reverse=True)
5 total_cost = 0
6 h_pieces = 1
7 v_pieces = 1
8 i, j = 0, 0
9 while i < len(horizontalCut) and j < len(verticalCut):
10 if horizontalCut[i] >= verticalCut[j]:
11 total_cost += horizontalCut[i] * v_pieces
12 h_pieces += 1
13 i += 1
14 else:
15 total_cost += verticalCut[j] * h_pieces
16 v_pieces += 1
17 j += 1
18 while i < len(horizontalCut):
19 total_cost += horizontalCut[i] * v_pieces
20 h_pieces += 1
21 i += 1
22 while j < len(verticalCut):
23 total_cost += verticalCut[j] * h_pieces
24 v_pieces += 1
25 j += 1
26 return total_costℹ
Complexity note: The complexity is dominated by the sorting steps for both cut arrays, making it efficient for larger inputs.
- 1Always cut the most expensive line first to minimize total cost.
- 2Sorting helps in efficiently determining the next cut.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.