Online store~25 min2s · 256 MBtarget O(n √n) time, O(n) spaceclassic twin: lc-279dp
An online store sells floor tiles in square packs. A pack holds 1 tile, 4 tiles, 9 tiles, 16 tiles, and so on: one pack size for every whole number squared. A customer needs exactly n tiles, and the store has as many packs of each size as the order needs.
Your team lead asks: "What is the fewest packs that hold exactly n tiles?"
Write fewest_packs(n).
k * k tiles for a whole number k of 1 or more. A customer may buy any number of packs of each size.n tiles.n.Input: n = 12
Output: 3Let packs[t] be the fewest packs that hold exactly t tiles. The last pack holds s * s tiles, for some s with s * s <= t. The packs before it hold the other t - s * s tiles. So packs[t] is one more than the smallest packs[t - s * s].
| t | Pack sizes that fit | Options | packs[t] |
|---|---|---|---|
| 0 | none | 0 | |
| 1 | 1 | packs[0] + 1 = 1 | 1 |
| 2 | 1 | packs[1] + 1 = 2 | 2 |
| 3 | 1 | packs[2] + 1 = 3 | 3 |
| 4 | 1, 4 | packs[3] + 1 = 4, packs[0] + 1 = 1 | 1 |
| 5 | 1, 4 | packs[4] + 1 = 2, packs[1] + 1 = 2 | 2 |
| 6 | 1, 4 | packs[5] + 1 = 3, packs[2] + 1 = 3 | 3 |
| 7 | 1, 4 | packs[6] + 1 = 4, packs[3] + 1 = 4 | 4 |
| 8 | 1, 4 | packs[7] + 1 = 5, packs[4] + 1 = 2 | 2 |
| 9 | 1, 4, 9 | packs[8] + 1 = 3, packs[5] + 1 = 3, packs[0] + 1 = 1 | 1 |
| 10 | 1, 4, 9 | packs[9] + 1 = 2, packs[6] + 1 = 4, packs[1] + 1 = 2 | 2 |
| 11 | 1, 4, 9 | packs[10] + 1 = 3, packs[7] + 1 = 5, packs[2] + 1 = 3 | 3 |
| 12 | 1, 4, 9 | packs[11] + 1 = 4, packs[8] + 1 = 3, packs[3] + 1 = 4 | 3 |
The answer is packs[12] = 3: three packs of 4 tiles.
Input: n = 13
Output: 2A pack of 4 and a pack of 9 hold 13 tiles: 2 packs.
Input: n = 16
Output: 116 is itself a square, so one pack holds it.
1 ≤ n ≤ 10,000The number 10,000 has 100 square pack sizes up to 10,000. Trying every order of packs never finishes. A table with one entry for each total up to 10,000, and at most 100 pack sizes for each entry, takes about a million steps.