#3218
Minimum Cost for Cutting Cake I
MediumArrayTwo PointersDynamic ProgrammingGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m + n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(m + n)Space O(1)
The optimal solution uses a greedy approach, where we always choose the cut that maximizes the area being cut at the minimum cost. By sorting the cut costs and using a two-pointer technique, we can efficiently calculate the total cost.
⚙️
Algorithm
3 steps- 1Step 1: Sort both horizontalCut and verticalCut arrays.
- 2Step 2: Initialize total cost, hCount, and vCount to 1 (since we start with one piece).
- 3Step 3: Use two pointers to iterate through both cut arrays, adding the cost of the cut multiplied by the current count of pieces in the opposite direction.
solution.py20 lines
1# Full working Python code
2class Solution:
3 def minCost(self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]) -> int:
4 horizontalCut.sort()
5 verticalCut.sort()
6 total_cost = 0
7 h_count = 1
8 v_count = 1
9 h_index = 0
10 v_index = 0
11 while h_index < len(horizontalCut) or v_index < len(verticalCut):
12 if (h_index < len(horizontalCut) and (v_index >= len(verticalCut) or horizontalCut[h_index] <= verticalCut[v_index])):
13 total_cost += horizontalCut[h_index] * v_count
14 h_count += 1
15 h_index += 1
16 else:
17 total_cost += verticalCut[v_index] * h_count
18 v_count += 1
19 v_index += 1
20 return total_costℹ
Complexity note: The time complexity is linear because we only traverse each cut array once after sorting, making it efficient compared to the brute-force approach.
- 1Choosing cuts that maximize the area being cut minimizes total cost.
- 2Sorting the cut costs allows for efficient selection of the next cut.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.