Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Cost for Cutting Cake I solution and explanation

MediumArrayDynamic ProgrammingGreedySorting7 min read58.5% acceptanceUpdated 9 Apr 2026
Minimum Cost for Cutting Cake I & II | Thought Process | Leetcode 3218 | 3219 | codestorywithMIKcodestorywithMIK · 39:26 · 6K viewsWatch on YouTube
9 more videos on this problem
  1. Minimum Cost for Cutting Cake I & II | Thought Process | Leetcode 3218 | 3219 | codestorywithMIKcodestorywithMIK · 39:26 · 6K views
  2. 3218 & 3219. Minimum Cost for Cutting Cake II & I | Greedy | Sorting @codeWithAryanBhaiAryan Mittal · 14:05 · 5K views
  3. 3218. Minimum Cost for Cutting Cake I | Weekly Leetcode 406codingMohan · 18:39 · 629 views
  4. 3218. Minimum Cost for Cutting Cake I (Leetcode Medium)Programming Live with Larry · 14:07 · 588 views
  5. Leetcode | Weekly Contest 406 | 3218 | 3219 | DP + Greedy Approach | C | D | Editorial | Solution.Pretest Passed · 17:10 · 268 views
  6. Minimum Cost for Cutting Cake I | Leetcode 3218 | Leetcode weekly-contest-406 | Java SolutionDeveloper Coder · 8:01 · 154 views
  7. 3218 & 3219. Minimum Cost for Cutting Cake i & ii | LeetCode Weekly Contest 406Amit Dhyani · 39:56 · 133 views
  8. 3218. Minimum Cost for Cutting Cake I (leetcode medium)Coder on A Farm · 20:10 · 112 views
  9. Leetcode 3218. Minimum Cost for Cutting Cake I - Python3 solutionEngineerCorner · 13:42 · 93 views
  10. Minimum Cost for Cutting Cake I || Leetcode Weekly 406 || C++ || GreedyAlim Khan - [ NIT RAIPUR ] · 12:24 · 24 views

The 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:

  1. Cut along a horizontal line i at a cost of horizontalCut[i].
  2. 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.

Example 1:

Input: m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]

Output: 13

Explanation:

  • Perform a cut on the vertical line 0 with cost 5, current total cost is 5.
  • Perform a cut on the horizontal line 0 on 3 x 1 subgrid with cost 1.
  • Perform a cut on the horizontal line 0 on 3 x 1 subgrid with cost 1.
  • Perform a cut on the horizontal line 1 on 2 x 1 subgrid with cost 3.
  • Perform a cut on the horizontal line 1 on 2 x 1 subgrid with cost 3.

The total cost is 5 + 1 + 1 + 3 + 3 = 13.

Example 2:

Input: m = 2, n = 2, horizontalCut = [7], verticalCut = [4]

Output: 15

Explanation:

  • Perform a cut on the horizontal line 0 with cost 7.
  • Perform a cut on the vertical line 0 on 1 x 2 subgrid with cost 4.
  • Perform a cut on the vertical line 0 on 1 x 2 subgrid with cost 4.

The total cost is 7 + 4 + 4 = 15.

Constraints:

  • 1 <= m, n <= 20
  • horizontalCut.length == m - 1
  • verticalCut.length == n - 1
  • 1 <= horizontalCut[i], verticalCut[i] <= 103

Approach overview

Problem Overview: You are given the costs of horizontal and vertical cuts needed to divide an m x n cake into 1x1 pieces. Each time you perform a cut, the cost is multiplied by the number of current segments in the opposite direction. The goal is to choose the order of cuts so the total cost is minimized.

Approach 1: Greedy with Priority Queue (O((m+n) log(m+n)) time, O(m+n) space)

The key observation: expensive cuts should be applied as early as possible. When you perform a cut later, it gets multiplied by more segments, which increases its total cost. To minimize the final sum, always perform the highest-cost cut first. Push all horizontal and vertical cuts into a max heap (priority queue) and repeatedly extract the largest cost. Maintain counters for horizontal and vertical segments. A horizontal cut contributes cost * verticalSegments, while a vertical cut contributes cost * horizontalSegments. This greedy strategy guarantees the minimum cost because it prevents expensive cuts from being multiplied by larger segment counts later.

This approach relies heavily on ideas from Greedy algorithms and works well because the cost contribution grows multiplicatively as segments increase.

Approach 2: Greedy with Sorting (O((m+n) log(m+n)) time, O(1) extra space)

Instead of using a heap, you can sort both cost arrays in descending order and simulate the greedy selection using two pointers. Compare the next largest horizontal and vertical cost and pick the larger one. Update the segment counters accordingly and accumulate the weighted cost. Sorting allows you to process cuts in decreasing order without maintaining a heap, making the implementation simpler while keeping the same asymptotic complexity.

This version primarily uses Array manipulation and Sorting. In practice it runs slightly faster due to lower constant factors compared to a priority queue.

Approach 3: Dynamic Programming (O(h * v) time, O(h * v) space)

A Dynamic Programming formulation considers how many horizontal and vertical cuts have already been performed. Let dp[i][j] represent the minimum cost after performing i horizontal and j vertical cuts. The next operation can either be another horizontal cut or a vertical cut. A horizontal cut adds horizontalCost[i] * (j + 1), while a vertical cut adds verticalCost[j] * (i + 1). Transition between states until all cuts are used. This explicitly explores interleavings of cut orders but is slower and uses more memory than the greedy strategy.

Recommended for interviews: The greedy strategy with sorting or a priority queue is the expected solution. It demonstrates the core insight: performing higher-cost cuts earlier prevents them from being multiplied by larger segment counts. Mentioning the DP formulation shows deeper understanding, but implementing the greedy approach efficiently is what interviewers typically look for.

Approach 1: Greedy Approach: Priority Queue

The key idea is to prioritize cuts with higher costs first, as these influence the subsequential cutting costs significantly. We use a priority queue (or max heap) to always perform the cut with the maximum cost from both available horizontal and vertical cuts. This ensures that more expensive cuts are counted first while there are more pieces to divide the cake into.

def min_cost_cuts(m, n, horizontal_cuts, vertical_cuts):
    horizontal_cuts.sort(reverse=True)
    vertical_cuts.sort(reverse=True)

    h_pieces, v_pieces, h, v, cost = 1, 1, 0, 0, 0

    while h < len(horizontal_cuts) and v < len(vertical_cuts):
        if horizontal_cuts[h] >= vertical_cuts[v]:
            cost += horizontal_cuts[h] * v_pieces
            h_pieces += 1
            h += 1
        else:
            cost += vertical_cuts[v] * h_pieces
            v_pieces += 1
            v += 1

    while h < len(horizontal_cuts):
        cost += horizontal_cuts[h] * v_pieces
        h += 1

    while v < len(vertical_cuts):
        cost += vertical_cuts[v] * h_pieces
        v += 1

    return cost

# Running an example
def main():
    m, n = 3, 2
    horizontal_cuts = [1, 3]
    vertical_cuts = [5]
    print(min_cost_cuts(m, n, horizontal_cuts, vertical_cuts))  # Output: 13

main()
import java.util.*;

public class MinCostCut {
    public int minCostCuts(int m, int n, int[] horizontalCuts, int[] verticalCuts) {
        Arrays.sort(horizontalCuts);
        Arrays.sort(verticalCuts);
        
        int h_pieces = 1, v_pieces = 1;
        int h = horizontalCuts.length - 1, v = verticalCuts.length - 1, cost = 0;
        
        while (h >= 0 && v >= 0) {
            if (horizontalCuts[h] >= verticalCuts[v]) {
                cost += horizontalCuts[h] * v_pieces;
                h_pieces++;
                h--;
            } else {
                cost += verticalCuts[v] * h_pieces;
                v_pieces++;
                v--;
            }
        }

        while (h >= 0) {
            cost += horizontalCuts[h] * v_pieces;
            h--;
        }

        while (v >= 0) {
            cost += verticalCuts[v] * h_pieces;
            v--;
        }

        return cost;
    }

    public static void main(String[] args) {
        MinCostCut mcc = new MinCostCut();
        int m = 3, n = 2;
        int[] horizontalCuts = {1, 3};
        int[] verticalCuts = {5};
        System.out.println(mcc.minCostCuts(m, n, horizontalCuts, verticalCuts));  // Output: 13
    }
}
#include <iostream>
#include <vector>
#include <algorithm>

int minCostCuts(int m, int n, std::vector<int>& horizontalCuts, std::vector<int>& verticalCuts) {
    std::sort(horizontalCuts.begin(), horizontalCuts.end(), std::greater<int>());
    std::sort(verticalCuts.begin(), verticalCuts.end(), std::greater<int>());
    
    int h_pieces = 1, v_pieces = 1;
    int h = 0, v = 0, cost = 0;
    
    while (h < horizontalCuts.size() && v < verticalCuts.size()) {
        if (horizontalCuts[h] >= verticalCuts[v]) {
            cost += horizontalCuts[h] * v_pieces;
            h_pieces++;
            h++;
        } else {
            cost += verticalCuts[v] * h_pieces;
            v_pieces++;
            v++;
        }
    }
    
    while (h < horizontalCuts.size()) {
        cost += horizontalCuts[h] * v_pieces;
        h++;
    }
    
    while (v < verticalCuts.size()) {
        cost += verticalCuts[v] * h_pieces;
        v++;
    }

    return cost;
}

int main() {
    int m = 3, n = 2;
    std::vector<int> horizontalCuts = {1, 3};
    std::vector<int> verticalCuts = {5};
    std::cout << minCostCuts(m, n, horizontalCuts, verticalCuts) << std::endl;  // Output: 13
    return 0;
}
function minCostCuts(m, n, horizontalCuts, verticalCuts) {
    horizontalCuts.sort((a, b) => b - a);
    verticalCuts.sort((a, b) => b - a);

    let h_pieces = 1, v_pieces = 1;
    let h = 0, v = 0, cost = 0;

    while (h < horizontalCuts.length && v < verticalCuts.length) {
        if (horizontalCuts[h] >= verticalCuts[v]) {
            cost += horizontalCuts[h] * v_pieces;
            h_pieces++;
            h++;
        } else {
            cost += verticalCuts[v] * h_pieces;
            v_pieces++;
            v++;
        }
    }

    while (h < horizontalCuts.length) {
        cost += horizontalCuts[h] * v_pieces;
        h++;
    }

    while (v < verticalCuts.length) {
        cost += verticalCuts[v] * h_pieces;
        v++;
    }

    return cost;
}

// Running an example
const m = 3, n = 2;
const horizontalCuts = [1, 3], verticalCuts = [5];
console.log(minCostCuts(m, n, horizontalCuts, verticalCuts));  // Output: 13;
#include <stdio.h>
#include <stdlib.h>

int cmpfunc(const void *a, const void *b) {
    return (*(int*)b - *(int*)a);
}

int minCostCuts(int m, int n, int* horizontalCuts, int horizontal_len, int* verticalCuts, int vertical_len) {
    qsort(horizontalCuts, horizontal_len, sizeof(int), cmpfunc);
    qsort(verticalCuts, vertical_len, sizeof(int), cmpfunc);
    
    int h_pieces = 1, v_pieces = 1;
    int h = 0, v = 0;
    int cost = 0;
    
    while (h < horizontal_len && v < vertical_len) {
        if (horizontalCuts[h] >= verticalCuts[v]) {
            cost += horizontalCuts[h] * v_pieces;
            h_pieces++;
            h++;
        } else {
            cost += verticalCuts[v] * h_pieces;
            v_pieces++;
            v++;
        }
    }
    
    while (h < horizontal_len) {
        cost += horizontalCuts[h] * v_pieces;
        h++;
    }
    
    while (v < vertical_len) {
        cost += verticalCuts[v] * h_pieces;
        v++;
    }

    return cost;
}

int main() {
    int m = 3, n = 2;
    int horizontalCuts[] = {1, 3};
    int verticalCuts[] = {5};
    printf("%d\n", minCostCuts(m, n, horizontalCuts, 2, verticalCuts, 1));  // Output: 13
    return 0;
}
using System;

public class MinCostCut {
    public int MinCostCuts(int m, int n, int[] horizontalCuts, int[] verticalCuts) {
        Array.Sort(horizontalCuts, (a, b) => b.CompareTo(a));
        Array.Sort(verticalCuts, (a, b) => b.CompareTo(a));

        int hPieces = 1, vPieces = 1;
        int h = 0, v = 0, cost = 0;

        while (h < horizontalCuts.Length && v < verticalCuts.Length) {
            if (horizontalCuts[h] >= verticalCuts[v]) {
                cost += horizontalCuts[h] * vPieces;
                hPieces++;
                h++;
            } else {
                cost += verticalCuts[v] * hPieces;
                vPieces++;
                v++;
            }
        }

        while (h < horizontalCuts.Length) {
            cost += horizontalCuts[h] * vPieces;
            h++;
        }

        while (v < verticalCuts.Length) {
            cost += verticalCuts[v] * hPieces;
            v++;
        }

        return cost;
    }

    public static void Main(string[] args) {
        MinCostCut mcc = new MinCostCut();
        int m = 3, n = 2;
        int[] horizontalCuts = new int[] {1, 3};
        int[] verticalCuts = new int[] {5};
        Console.WriteLine(mcc.MinCostCuts(m, n, horizontalCuts, verticalCuts));  // Output: 13
    }
}

The Python implementation similarly sorts both cost arrays in descending order and uses a greedy choice to cut first with the highest cost. This minimized total expenditure methodically splits either horizontally or vertically as needed.

Complexity

Time Complexity: O((m + n) log(m + n)), Space complexity: O(1).

Try this approach in the editor

Approach 2: Dynamic Programming Approach

In the dynamic programming approach, we define a 2D DP array where dp[i][j] represents the minimal cost to cut the i x j subgrid into 1 x 1 pieces. This approach utilizes memoization to store previously calculated results efficiently. It systematically builds the solution by evaluating subproblems and their optimal solutions.

def min_cost_cut_dp(m, n, horizontal_cuts, vertical_cuts):
    dp = [[0] * n for _ in range(m)]

    for i in range(1, m):
        dp[i][0] = dp[i-1][0] + horizontal_cuts[i-1] * n
    for j in range(1, n):
        dp[0][j] = dp[0][j-1] + vertical_cuts[j-1] * m

    for i in range(1, m):
        for j in range(1, n):
            dp[i][j] = min(dp[i-1][j] + horizontal_cuts[i-1] * (j + 1),
                                dp[i][j-1] + vertical_cuts[j-1] * (i + 1))

    return dp[m-1][n-1]

# Running an example
def main():
    m, n = 3, 2
    horizontal_cuts = [1, 3]
    vertical_cuts = [5]
    print(min_cost_cut_dp(m, n, horizontal_cuts, vertical_cuts))  # Output: 13

main()
import java.util.*;

public class MinCostCut {
    public int minCostCutDP(int m, int n, int[] horizontalCuts, int[] verticalCuts) {
        int[][] dp = new int[m][n];
        dp[0][0] = 0;

        for (int i = 1; i < m; i++) dp[i][0] = dp[i-1][0] + horizontalCuts[i-1] * n;
        for (int j = 1; j < n; j++) dp[0][j] = dp[0][j-1] + verticalCuts[j-1] * m;

        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                dp[i][j] = Math.min(dp[i-1][j] + horizontalCuts[i-1] * (j + 1),
                                    dp[i][j-1] + verticalCuts[j-1] * (i + 1));

        return dp[m-1][n-1];
    }

    public static void main(String[] args) {
        MinCostCut mcc = new MinCostCut();
        int m = 3, n = 2;
        int[] horizontalCuts = {1, 3};
        int[] verticalCuts = {5};
        System.out.println(mcc.minCostCutDP(m, n, horizontalCuts, verticalCuts));  // Output: 13
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int minCostCutDP(int m, int n, vector<int>& horizontalCuts, vector<int>& verticalCuts) {
    vector<vector<int>> dp(m, vector<int>(n, INT_MAX));

    dp[0][0] = 0;
    for (int i = 1; i < m; i++) dp[i][0] = dp[i-1][0] + horizontalCuts[i-1] * n;
    for (int j = 1; j < n; j++) dp[0][j] = dp[0][j-1] + verticalCuts[j-1] * m;

    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[i][j] = min(dp[i-1][j] + horizontalCuts[i-1] * (j+1),
                            dp[i][j-1] + verticalCuts[j-1] * (i+1));
        }
    }
    return dp[m-1][n-1];
}

int main() {
    int m = 3, n = 2;
    vector<int> horizontalCuts = {1, 3};
    vector<int> verticalCuts = {5};
    cout << minCostCutDP(m, n, horizontalCuts, verticalCuts) << endl;  // Output: 13
    return 0;
}
function minCostCutDP(m, n, horizontalCuts, verticalCuts) {
    const dp = Array.from({ length: m }, () => Array(n).fill(0));

    for (let i = 1; i < m; i++) {
        dp[i][0] = dp[i-1][0] + horizontalCuts[i-1] * n;
    }
    for (let j = 1; j < n; j++) {
        dp[0][j] = dp[0][j-1] + verticalCuts[j-1] * m;
    }

    for (let i = 1; i < m; i++) {
        for (let j = 1; j < n; j++) {
            dp[i][j] = Math.min(
                dp[i-1][j] + horizontalCuts[i-1] * (j + 1),
                dp[i][j-1] + verticalCuts[j-1] * (i + 1)
            );
        }
    }

    return dp[m-1][n-1];
}

// Running an example
const m = 3, n = 2;
const horizontalCuts = [1, 3], verticalCuts = [5];
console.log(minCostCutDP(m, n, horizontalCuts, verticalCuts));  // Output: 13;
#include <stdio.h>
#include <limits.h>

int minCostCutDP(int m, int n, int* horizontalCuts, int horizontal_len, int* verticalCuts, int vertical_len) {
    int dp[m][n];
    for(int i = 0; i < m; i++)
        for(int j = 0; j < n; j++)
            dp[i][j] = 0;

    for(int i = 1; i < m; i++) {
        dp[i][0] = dp[i-1][0] + horizontalCuts[i-1] * n;
    }
    for(int j = 1; j < n; j++) {
        dp[0][j] = dp[0][j-1] + verticalCuts[j-1] * m;
    }

    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[i][j] = dp[i-1][j] + horizontalCuts[i-1] * (j + 1);
            dp[i][j] = dp[i][j-1] + verticalCuts[j-1] * (i + 1);
        }
    }

    return dp[m-1][n-1];
}

int main() {
    int m = 3, n = 2;
    int horizontalCuts[] = {1, 3};
    int verticalCuts[] = {5};
    printf("%d\n", minCostCutDP(m, n, horizontalCuts, 2, verticalCuts, 1));  // Output: 13
    return 0;
}
using System;

public class MinCostCut {
    public int MinCostCutDP(int m, int n, int[] horizontalCuts, int[] verticalCuts) {
        int[,] dp = new int[m, n];
        dp[0, 0] = 0;

        for (int i = 1; i < m; i++) dp[i, 0] = dp[i-1, 0] + horizontalCuts[i-1] * n;
        for (int j = 1; j < n; j++) dp[0, j] = dp[0, j-1] + verticalCuts[j-1] * m;

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i, j] = Math.Min(dp[i-1, j] + horizontalCuts[i-1] * (j + 1),
                                    dp[i, j-1] + verticalCuts[j-1] * (i + 1));
            }
        }

        return dp[m-1, n-1];
    }

    public static void Main(string[] args) {
        MinCostCut mcc = new MinCostCut();
        int m = 3, n = 2;
        int[] horizontalCuts = {1, 3};
        int[] verticalCuts = {5};
        Console.WriteLine(mcc.MinCostCutDP(m, n, horizontalCuts, verticalCuts));  // Output: 13
    }
}

The Python implementation constructs a two-dimensional list (array) structure suited for dynamic programming and iteratively evaluates each possible cut operation's cost. By checking subgrid solutions, we reach the final top-level solution efficiently.

Complexity

Time Complexity: O(m * n), Space complexity: O(m * n).

Try this approach in the editor

Approach 3: Greedy + Two Pointers

For a given position, the earlier you cut, the fewer cuts are needed, so it is clear that positions with higher costs should be cut earlier.

Therefore, we can sort the arrays horizontalCut and verticalCut in descending order, and then use two pointers i and j to point to the costs in horizontalCut and verticalCut, respectively. Each time, we choose the position with the larger cost to cut, while updating the corresponding number of rows and columns.

Each time a horizontal cut is made, if the number of columns before the cut was v, then the cost of this cut is horizontalCut[i] times v, and then the number of rows h is incremented by one; similarly, each time a vertical cut is made, if the number of rows before the cut was h, then the cost of this cut is verticalCut[j] times h, and then the number of columns v is incremented by one.

Finally, when both i and j reach the end, return the total cost.

The time complexity is O(m times log m + n times log n), and the space complexity is O(log m + log n). Here, m and n are the lengths of horizontalCut and verticalCut, respectively.

function minimumCost(m: number, n: number, horizontalCut: number[], verticalCut: number[]): number {
    horizontalCut.sort((a, b) => b - a);
    verticalCut.sort((a, b) => b - a);
    let ans = 0;
    let [i, j] = [0, 0];
    let [h, v] = [1, 1];
    while (i < m - 1 || j < n - 1) {
        if (j === n - 1 || (i < m - 1 && horizontalCut[i] > verticalCut[j])) {
            ans += horizontalCut[i] * v;
            h++;
            i++;
        } else {
            ans += verticalCut[j] * h;
            v++;
            j++;
        }
    }
    return ans;
}
func minimumCost(m int, n int, horizontalCut []int, verticalCut []int) (ans int) {
	sort.Sort(sort.Reverse(sort.IntSlice(horizontalCut)))
	sort.Sort(sort.Reverse(sort.IntSlice(verticalCut)))
	i, j := 0, 0
	h, v := 1, 1
	for i < m-1 || j < n-1 {
		if j == n-1 || (i < m-1 && horizontalCut[i] > verticalCut[j]) {
			ans += horizontalCut[i] * v
			h++
			i++
		} else {
			ans += verticalCut[j] * h
			v++
			j++
		}
	}
	return
}
impl Solution {
    pub fn minimum_cost(m: i32, n: i32, mut horizontal_cut: Vec<i32>, mut vertical_cut: Vec<i32>) -> i32 {
        horizontal_cut.sort();
        vertical_cut.sort();
        let (mut i, mut j) = ((m - 2) as isize, (n - 2) as isize);
        let (mut h, mut v) = (1, 1);
        let mut ans = 0;

        while i >= 0 || j >= 0 {
            if j < 0 || (i >= 0 && horizontal_cut[i as usize] > vertical_cut[j as usize]) {
                ans += horizontal_cut[i as usize] * v;
                i -= 1;
                h += 1;
            } else {
                ans += vertical_cut[j as usize] * h;
                j -= 1;
                v += 1;
            }
        }

        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Greedy Approach: Priority Queue

Time Complexity: O((m + n) log(m + n)), Space complexity: O(1).

Dynamic Programming Approach

Time Complexity: O(m * n), Space complexity: O(m * n).

Greedy + Two Pointers–

Complexity analysis

ApproachTimeSpaceWhen to Use
Greedy with Priority QueueO((m+n) log(m+n))O(m+n)When you want a straightforward greedy implementation that always selects the largest remaining cut.
Greedy with SortingO((m+n) log(m+n))O(1)Most common interview solution; simpler and faster than heap-based implementation.
Dynamic ProgrammingO(h * v)O(h * v)Useful for understanding all possible cut orders or when demonstrating DP reasoning.

Frequently asked questions

Is Minimum Cost for Cutting Cake I easy or hard?

Minimum Cost for Cutting Cake I is typically classified as Medium difficulty. The implementation is straightforward once you recognize the greedy insight, but identifying why the largest-cost-first strategy minimizes the total cost requires algorithmic intuition.

Minimum Cost for Cutting Cake I Python/Java solution

Python and Java implementations usually sort both cost arrays in descending order and iterate with two pointers. At each step the algorithm selects the larger cut cost, multiplies it by the current number of opposite-direction segments, and updates the segment count. The logic is identical across Python, Java, C++, and JavaScript.

How to solve Minimum Cost for Cutting Cake I in O(n log n)?

Sort the horizontal and vertical cut costs in descending order. Maintain counters for horizontal and vertical segments. At each step choose the larger remaining cost, add its weighted contribution (cost multiplied by current segments in the opposite direction), and update the segment count. This greedy ordering ensures the total cost is minimized with O((m+n) log(m+n)) complexity.

What is the best approach for Minimum Cost for Cutting Cake I?

The optimal approach is a greedy strategy that always performs the highest-cost cut first. By sorting the horizontal and vertical cut costs in descending order (or using a max heap), you ensure expensive cuts happen when the number of segments is small. This minimizes the multiplication effect that occurs as the cake gets divided. The time complexity is O((m+n) log(m+n)).

Is Minimum Cost for Cutting Cake I asked at Google/Amazon/Meta?

This problem is a variation of the classic board-cutting greedy problem frequently asked in interviews at companies like Amazon and Google. The key concept—choosing the largest cost first to minimize multiplicative impact—appears in many greedy interview questions.

What data structure is used in Minimum Cost for Cutting Cake I?

The solution typically uses arrays combined with sorting or a max priority queue. Sorting enables processing costs in descending order, while a priority queue allows dynamically selecting the highest remaining cut. Both implementations rely on greedy decision making.

What is the time complexity of Minimum Cost for Cutting Cake I?

The optimal greedy solution runs in O((m+n) log(m+n)) time due to sorting or priority queue operations. Each cut is processed exactly once while maintaining segment counts. Space complexity ranges from O(1) with sorting to O(m+n) when using a priority queue.

Comments

Now write it yourselfClose this page and solve Minimum Cost for Cutting Cake I in the editor, without looking.
Practise Minimum Cost for Cutting Cake I