Ctrl K

Breaking a Chocolate Bar

Medium
A chocolate bar is made of rows × cols squares, and you need to break it into single squares. There are rows - 1 horizontal break lines between the rows of squares and cols - 1 vertical ones between the columns. Breaking a piece along horizontal line i costs row_lines[i], and along vertical line j costs col_lines[j]. The price depends only on the line, not on the size of the piece. In one step you take any piece that is not yet a single square and break it along one line that crosses it, producing two pieces. If a line crosses several pieces, each of them has to be broken (and paid for) separately. Return the minimum total cost of breaking the whole bar into 1 × 1 squares.
Example 1
rows=2, cols=3, row_lines=[4], col_lines=[2, 6] → 18

Start with the priciest line: column line 1 for 6. Then the row line for 4, which now runs through both pieces: 4 + 4. Column line 0 for 2 is left, broken in both row strips: 2 + 2. Total 6 + 8 + 4 = 18.

Example 2
rows=3, cols=1, row_lines=[5, 1], col_lines=[] → 6

The bar is a single strip, so each line is broken exactly once: 5 + 1 = 6.

Example 3
rows=1, cols=1, row_lines=[], col_lines=[] → 0
Constraints
  • 1 ≤ rows, cols ≤ 500
  • len(row_lines) = rows - 1
  • len(col_lines) = cols - 1
  • 1 ≤ row_lines[i], col_lines[j] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Meetings to Cancel MediumLongest Chain of Segments MediumA Haul That Splits Three Ways MediumStrongest Product Team MediumBiggest Number Divisible by Three Hard
loading Python…
Input
rows=2, cols=3, row_lines=[4], col_lines=[2, 6]
Expected
18

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