710038. Minimum Cost to cut a board into squares

Medium

Minimum Cost to cut a board into squares

Slug: minimum-cost-to-cut-a-board-into-squares

Difficulty: Medium

Topic Tags: Greedy, Algorithms

Company Tags: None

Summary

We are given a rectangular board of size n x m, and we want to cut it into the maximum number of identical square pieces. The cost of cutting each piece is proportional to its side length. Our goal is to find the minimum total cost required to cut the board into squares.

The problem involves greedy algorithms, as we need to make a sequence of decisions that do not depend on future choices. This type of problem often requires us to consider the optimal substructure of the problem and make decisions based on local information.

Detailed Explanation

To solve this problem, we can use a greedy algorithm. The idea is to always cut the board into squares with the largest possible side length, as long as it is possible to do so. This way, we minimize the total cost required to cut the board.

Here's the step-by-step breakdown of the solution:

  1. Initialize the minimum and maximum side lengths for the squares (minSide and maxSide) to 1 and sqrt(n*m) respectively.
  2. While it is possible to cut the board into squares with a side length greater than or equal to minSide, do so. This means we need to find the largest square that can be cut from the remaining board.
  3. Update minSide to be one unit larger than the side length of the last cut square.
  4. Repeat step 2 until it is not possible to cut the board into squares with a side length greater than or equal to minSide.
  5. The total cost required to cut the board into squares is the sum of the costs for each square, which is proportional to its side length.

The time complexity of this algorithm is O(sqrt(nm)), as in the worst case we need to iterate sqrt(nm) times to find the largest possible square that can be cut from the remaining board. The space complexity is O(1), as we only use a constant amount of space to store the minimum and maximum side lengths.

Optimized Solutions

Java

View on GeeksforGeeks
public int minCost(int n, int m) {
    int minSide = 1;
    int maxSide = (int)Math.sqrt(n*m);
    int cost = 0;

    while (minSide <= maxSide) {
        int sideLength = minSide;
        while ((n / sideLength) * (m / sideLength) > 0) {
            n -= n / sideLength;
            m -= m / sideLength;
            cost += sideLength * sideLength;
        }
        minSide++;
    }

    return cost;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.