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:

  • horizontalCut of size m - 1, where horizontalCut[i] represents the cost to cut along the horizontal line i.
  • verticalCut of size n - 1, where verticalCut[j] represents the cost to cut along the vertical line j.

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 i at a cost of horizontalCut[i].
  • Cut along a vertical line j at a cost of verticalCut[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
Minimum Cost Cake Cutting Problem4×3 CakeH:2H:1V:1V:3Greedy Strategy1. Sort cuts: [3,2,1,1]2. V-cut(3): 3×1 = 33. H-cut(2): 2×2 = 44. Others: 1+1 = 2Total Cost8(3+4+1)💡 Make expensive cuts early to minimize multiplication effectResult: Optimal cost using greedy approach
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
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
420 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen