Show problems as
Classic problem #279MediumMathDynamic ProgrammingBreadth-First SearchKnapsack ProblemComplete Knapsack

Perfect Squares

Real-world version: Fewest Square Tiles
Tracked in this browser only
Read Perfect Squares on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A courtyard crew paves a strip whose surface measures exactly area square metres. The supplier stocks square slabs in every whole-metre side length: 1 by 1, 2 by 2, 3 by 3 and so on, in unlimited quantity, and a slab of side s covers s * s square metres.

The crew lays slabs so that the covered surface adds up to area with nothing left over and nothing overlapping. Only the areas matter here, not how the slabs sit next to each other, and the same side length may be used as often as needed.

Given area, return the smallest number of slabs whose areas add up to exactly area.

Examples

Example 1

Input
area = 28
Output
4

Three slabs of side 2 and one of side 4 cover 4 + 4 + 4 + 16, which is 28 square metres with four slabs.

Example 2

Input
area = 18
Output
2

Two slabs of side 3 cover 9 + 9, which is exactly 18 square metres.

Constraints

  • 1 <= area <= 10^4

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def fewest_square_tiles(area: int) -> int:
Java
public int fewestSquareTiles(int area)