PerfectSquares   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
eloc 19
c 2
b 0
f 0
dl 0
loc 34
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A numSquares() 0 14 4
A numSquares2() 0 16 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class PerfectSquares
8
{
9
    public static function numSquares(int $n): int
10
    {
11
        if ($n <= 0) {
12
            return 0;
13
        }
14
        $dp = array_fill(0, $n + 1, PHP_INT_MAX);
15
        $dp[0] = 0;
16
        for ($i = 1; $i <= $n; $i++) {
17
            for ($j = 1; $j * $j <= $i; $j++) {
18
                $dp[$i] = min($dp[$i], $dp[$i - $j * $j] + 1);
19
            }
20
        }
21
22
        return array_pop($dp);
23
    }
24
25
    public static function numSquares2(int $n): int
26
    {
27
        if ($n <= 0) {
28
            return 0;
29
        }
30
        $dp = [0];
31
        while (count($dp) <= $n) {
32
            $cnt = count($dp);
33
            $tmp = PHP_INT_MAX;
34
            for ($i = 1; $i * $i <= $cnt; $i++) {
35
                $tmp = min($tmp, $dp[$cnt - $i * $i] + 1);
36
            }
37
            $dp[] = $tmp;
38
        }
39
40
        return $dp[$n];
41
    }
42
}
43