Minimum Cost for Cutting Cake I Problem
Description
LeetCode Problem 3218.
There is an m x n cake that needs to be cut into 1 x 1 pieces.
You are given integers m, n, and two arrays:
horizontalCutof sizem - 1, wherehorizontalCut[i]represents the cost to cut along the horizontal linei.verticalCutof sizen - 1, whereverticalCut[j]represents the cost to cut along the vertical linej.
In one operation, you can choose any piece of cake that is not yet a 1 x 1 square and perform one of the following cuts:
- Cut along a horizontal line
iat a cost ofhorizontalCut[i]. - Cut along a vertical line
jat a cost ofverticalCut[j].
After the cut, the piece of cake is divided into two distinct pieces.
The cost of a cut depends only on the initial cost of the line and does not change.
Return the minimum total cost to cut the entire cake into 1 x 1 pieces.
Example 1:
Input: m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]
Output: 13
Explanation:

- Perform a cut on the vertical line 0 with cost 5, current total cost is 5.
- Perform a cut on the horizontal line 0 on 3 x 1 subgrid with cost 1.
- Perform a cut on the horizontal line 0 on 3 x 1 subgrid with cost 1.
- Perform a cut on the horizontal line 1 on 2 x 1 subgrid with cost 3.
- Perform a cut on the horizontal line 1 on 2 x 1 subgrid with cost 3.
The total cost is 5 + 1 + 1 + 3 + 3 = 13.
Example 2:
Input: m = 2, n = 2, horizontalCut = [7], verticalCut = [4]
Output: 15
Explanation:
- Perform a cut on the horizontal line 0 with cost 7.
- Perform a cut on the vertical line 0 on 1 x 2 subgrid with cost 4.
- Perform a cut on the vertical line 0 on 1 x 2 subgrid with cost 4.
The total cost is 7 + 4 + 4 = 15.
Constraints:
1 <= m, n <= 20horizontalCut.length == m - 1verticalCut.length == n - 11 <= horizontalCut[i], verticalCut[i] <= 10^3
Solution
Approach: Greedy + Two Pointers
The earlier a cut is made, the fewer pieces it has to cross, so the most expensive cuts should come first.
Sort horizontalCut and verticalCut in descending order and keep two pointers i and j. At each step take the larger of the two current costs. A horizontal cut costs horizontalCut[i] * v, where v is the number of vertical pieces so far, and then the number of horizontal pieces h grows by one. A vertical cut costs verticalCut[j] * h, and then v grows by one. Stop when all cuts are used and return the total.
Complexity: time O(m log m + n log n), space O(log m + log n) for sorting.
class Solution:
def minimumCost(
self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]
) -> int:
horizontalCut.sort(reverse=True)
verticalCut.sort(reverse=True)
ans = i = j = 0
h = v = 1
while i < m - 1 or j < n - 1:
if j == n - 1 or (i < m - 1 and horizontalCut[i] > verticalCut[j]):
ans += horizontalCut[i] * v
h, i = h + 1, i + 1
else:
ans += verticalCut[j] * h
v, j = v + 1, j + 1
return ans