CHOCOLA –Chocolate

Pattern: Candy and assign cookies

medium

Breaking a chocolate bar into single squares is the board-cutting problem: each break costs its price times the pieces it runs across. Make the dearest breaks first, taking the dearer of the next horizontal and vertical break each time.

The problem

A bar is broken into single squares. x lists the costs of the breaks along one direction and y along the other; a break costs its price times the number of pieces it goes through. Return the least total cost. x = [2, 1, 3, 1, 4], y = [4, 1, 2] gives 42. The SPOJ version reads several bars; here each call is one bar.

Think first

  • Which problem in this section is the same?
  • What multiplies a break's cost?
  • When should expensive breaks happen?

Hints

    Brute force, and why it fails

    Try every order of breaks: factorial.

    The key insight

    A break's multiplier only grows, so the dearest breaks must come first.

    Dry run

    xPieces1
    yPieces1

    x = [2, 1, 3, 1, 4], y = [4, 1, 2]. Sorted high to low: x 4 3 2 1 1, y 4 2 1.

    Step 1 of 3

    The plan

    sort x and y from high to low
    repeatedly take the dearer next break, multiplied by the pieces in the other direction
    

    Complexity

    Time
    O(m log m + n log n)
    Space
    O(m + n)

    Two sorts and a merge.

    Edge cases

    • A 1 × n bar: only one direction.
    • Equal prices.
    • No breaks: 0.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long chocolate(int[] x, int[] y) {
            Integer[] a = new Integer[x.length], b = new Integer[y.length];
            for (int i = 0; i < x.length; i++) a[i] = x[i];
            for (int i = 0; i < y.length; i++) b[i] = y[i];
            Arrays.sort(a, Collections.reverseOrder());   // dearest cuts first, while they cross the fewest pieces
            Arrays.sort(b, Collections.reverseOrder());
            int i = 0, j = 0;
            long xPieces = 1, yPieces = 1, total = 0;
            while (i < a.length || j < b.length) {
                if (j == b.length || (i < a.length && a[i] >= b[j])) {
                    total += a[i++] * yPieces;      // an x cut runs across every y piece
                    xPieces++;
                } else {
                    total += b[j++] * xPieces;      // a y cut runs across every x piece
                    yPieces++;
                }
            }
            return total;
        }
    }

    C++

    class Solution {
    public:
        long long chocolate(vector<int>& x, vector<int>& y) {
            vector<int> a(x), b(y);
            sort(a.rbegin(), a.rend());             // dearest cuts first, while they cross the fewest pieces
            sort(b.rbegin(), b.rend());
            size_t i = 0, j = 0;
            long long xPieces = 1, yPieces = 1, total = 0;
            while (i < a.size() || j < b.size()) {
                if (j == b.size() || (i < a.size() && a[i] >= b[j])) {
                    total += a[i++] * yPieces;      // an x cut runs across every y piece
                    xPieces++;
                } else {
                    total += b[j++] * xPieces;      // a y cut runs across every x piece
                    yPieces++;
                }
            }
            return total;
        }
    };

    Python

    class Solution:
        def chocolate(self, x: list[int], y: list[int]) -> int:
            a, b = sorted(x, reverse=True), sorted(y, reverse=True)   # dearest cuts first
            i = j = 0
            x_pieces = y_pieces = 1
            total = 0
            while i < len(a) or j < len(b):
                if j == len(b) or (i < len(a) and a[i] >= b[j]):
                    total += a[i] * y_pieces        # an x cut runs across every y piece
                    x_pieces += 1
                    i += 1
                else:
                    total += b[j] * x_pieces        # a y cut runs across every x piece
                    y_pieces += 1
                    j += 1
            return total

    Common mistakes

    • Multiplying by the pieces in the same direction.
    • Sorting ascending.

    Similar problems