Minimum Cost for Cutting Cake I

medium array greedy sorting

Problem

You have an m × n cake that must be sliced into 1 × 1 pieces. There are m - 1 horizontal lines and n - 1 vertical lines you may cut along, with prices horizontalCut[i] and verticalCut[j]. Each time you slice along a line, the cut runs across every piece currently sitting on that line, and you pay its price once for each of those pieces. Return the minimum total cost to cut the whole cake into unit squares.

Inputm=3, n=2, horizontalCut=[1,3], verticalCut=[5]
Output13
Cut vertical (5) first while the cake is one tall piece → 5. Now there are 2 columns, so each horizontal cut crosses 2 pieces: 3×2=6 then 1×2=2. Total 5+6+2=13.

def minimum_cost(m, n, horizontal_cut, vertical_cut):
    cuts = [(c, "h") for c in horizontal_cut] + [(c, "v") for c in vertical_cut]
    cuts.sort(reverse=True)
    h_pieces, v_pieces = 1, 1
    total = 0
    for cost, kind in cuts:
        if kind == "h":
            total += cost * v_pieces
            h_pieces += 1
        else:
            total += cost * h_pieces
            v_pieces += 1
    return total
function minimumCost(m, n, horizontalCut, verticalCut) {
  const cuts = horizontalCut.map(c => [c, "h"])
    .concat(verticalCut.map(c => [c, "v"]));
  cuts.sort((a, b) => b[0] - a[0]);
  let hPieces = 1, vPieces = 1, total = 0;
  for (const [cost, kind] of cuts) {
    if (kind === "h") { total += cost * vPieces; hPieces++; }
    else { total += cost * hPieces; vPieces++; }
  }
  return total;
}
class Solution {
    public long minimumCost(int m, int n, int[] horizontalCut, int[] verticalCut) {
        int[][] cuts = new int[m - 1 + n - 1][2];
        int idx = 0;
        for (int c : horizontalCut) cuts[idx++] = new int[]{ c, 0 };
        for (int c : verticalCut) cuts[idx++] = new int[]{ c, 1 };
        Arrays.sort(cuts, (a, b) -> b[0] - a[0]);
        long hPieces = 1, vPieces = 1, total = 0;
        for (int[] cut : cuts) {
            if (cut[1] == 0) { total += (long) cut[0] * vPieces; hPieces++; }
            else { total += (long) cut[0] * hPieces; vPieces++; }
        }
        return total;
    }
}
long long minimumCost(int m, int n, vector<int>& horizontalCut, vector<int>& verticalCut) {
    vector<pair<int, int>> cuts;
    for (int c : horizontalCut) cuts.push_back({ c, 0 });
    for (int c : verticalCut) cuts.push_back({ c, 1 });
    sort(cuts.rbegin(), cuts.rend());
    long long hPieces = 1, vPieces = 1, total = 0;
    for (auto& cut : cuts) {
        if (cut.second == 0) { total += (long long) cut.first * vPieces; hPieces++; }
        else { total += (long long) cut.first * hPieces; vPieces++; }
    }
    return total;
}
Time: O(k log k) Space: O(k)