Ctrl K

Slicing a Sheet Cake

Hard
A rectangular cake of size rows × cols has to be cut into 1 × 1 pieces. Horizontal lines 0 … rows − 2 run between the rows, and vertical lines 0 … cols − 2 run between the columns. Cutting along horizontal line i costs row_cuts[i], along vertical line j costs col_cuts[j]. You cut one piece at a time: take any piece that is not yet 1 × 1 and split it in two along one line, all the way across. The price depends only on the line, not on the size of the piece, but if a line crosses several pieces, each of them is cut and paid for separately. Return the minimum total cost of cutting the whole cake.
Example 1
rows=2, cols=3, row_cuts=[4], col_cuts=[1, 2] → 10

First cut along the horizontal line for 4. Then vertical line 1 runs through two pieces: 2 + 2. The last line 0 also goes through two pieces: 1 + 1. In total 4 + 4 + 2 = 10.

Example 2
rows=3, cols=1, row_cuts=[5, 2], col_cuts=[] → 7

The cake is a strip of three squares, so each of the two lines is cut once: 5 + 2 = 7.

Example 3
rows=1, cols=1, row_cuts=[], col_cuts=[] → 0

The cake is already 1 × 1, there is nothing to cut.

Constraints
  • 1 ≤ rows, cols ≤ 10⁵
  • len(row_cuts) = rows − 1
  • len(col_cuts) = cols − 1
  • 1 ≤ row_cuts[i], col_cuts[j] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsGrowing Capital Project by Project HardDistinct Word Shorthands HardMost Orders by Their Deadlines HardNarrowest Range Touching Every List HardTwo Marks in Every Range Hard
loading Python…
Input
rows=2, cols=3, row_cuts=[4], col_cuts=[1, 2]
Expected
10

Run checks the first 3 tests in your browser. Submit checks all 29 tests on the server, hidden ones included.