CoinChange   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 15
eloc 21
c 2
b 0
f 0
dl 0
loc 38
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B coinChange2() 0 17 8
B coinChange() 0 17 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class CoinChange
8
{
9
    public static function coinChange(array $coins, int $amount): int
10
    {
11
        [$m, $n] = [$amount + 1, count($coins)];
12
        if ($amount <= 0 || $n <= 0) {
13
            return 0;
14
        }
15
        [$dp, $dp[0]] = [array_fill(0, $m, $m), 0];
16
        for ($i = 1; $i < $m; $i++) {
17
            for ($j = 0; $j < $n; $j++) {
18
                $coin = $coins[$j];
19
                if ($coin <= $i) {
20
                    $dp[$i] = min($dp[$i], $dp[$i - $coin] + 1);
21
                }
22
            }
23
        }
24
25
        return $dp[$amount] > $amount ? -1 : $dp[$amount];
26
    }
27
28
    public static function coinChange2(array $coins, int $amount): int
29
    {
30
        [$m, $n] = [$amount + 1, count($coins)];
31
        if ($amount <= 0 || $n <= 0) {
32
            return 0;
33
        }
34
        [$dp, $max] = [array_fill(0, $m, 0), PHP_INT_MAX];
35
        for ($i = 1; $i < $m; $i++) {
36
            $dp[$i] = $max;
37
            foreach ($coins as $coin) {
38
                if ($coin <= $i && $dp[$i - $coin] !== $max) {
39
                    $dp[$i] = min($dp[$i], $dp[$i - $coin] + 1);
40
                }
41
            }
42
        }
43
44
        return $dp[$amount] === $max ? -1 : $dp[$amount];
45
    }
46
}
47