Minimum Cost for Cutting Cake I - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
m = 3, n = 2, horizontalCut = [1,1], verticalCut = [1]
›
Output:
4
💡 Note:
Make vertical cut first (cost 1×1=1), then two horizontal cuts (cost 1×2=2 each), total = 1+2+2 = 5. Actually optimal is to alternate cuts for cost 4.
Example 2 — Different Costs
$
Input:
m = 4, n = 3, horizontalCut = [1,2,1], verticalCut = [1,3]
›
Output:
8
💡 Note:
Sort cuts: [3,2,1,1,1]. Make V-cut cost 3 first (3×1=3), H-cut cost 2 (2×2=4), then remaining cuts cost 1 each.
Example 3 — Equal Costs
$
Input:
m = 2, n = 2, horizontalCut = [7], verticalCut = [4]
›
Output:
11
💡 Note:
Two cuts needed: Make H-cut first (7×1=7), then V-cut (4×1=4), total = 7+4 = 11.
Constraints
- 1 ≤ m, n ≤ 20
- horizontalCut.length == m - 1
- verticalCut.length == n - 1
- 1 ≤ horizontalCut[i], verticalCut[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
4×3 cake with horizontal cuts [2,1,1] and vertical cuts [1,3]
2
Strategy
Sort all cuts by cost and make expensive cuts first
3
Output
Minimum total cost is 8
Key Takeaway
🎯 Key Insight: Make expensive cuts first when they affect fewer pieces to minimize total cost
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code