Issues (64)

src/leetcode/Triangle.php (1 issue)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class Triangle
8
{
9
    public static function minimumTotal(array $triangle)
10
    {
11
        if (0 === $n = count($triangle)) {
12
            return $n;
13
        }
14
        $dp = [];
15
        for ($i = 0; $i < count($triangle[$n - 1]); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
16
            $dp[$i] = $triangle[$n - 1][$i];
17
        }
18
        for ($i = $n - 2; $i >= 0; $i--) {
19
            for ($j = 0; $j <= $i; $j++) {
20
                $dp[$j] = min($dp[$j], $dp[$j + 1]) + $triangle[$i][$j];
21
            }
22
        }
23
24
        return $dp[0];
25
    }
26
27
    public static function minimumTotal2(array $triangle)
28
    {
29
        if (0 === $n = count($triangle)) {
30
            return $n;
31
        }
32
33
        $ans = $triangle[$n - 1];
34
        for ($i = $n - 2; $i >= 0; $i--) {
35
            for ($j = 0; $j <= $i; $j++) {
36
                $ans[$j] = $triangle[$i][$j] + min($ans[$j], $ans[$j + 1]);
37
            }
38
        }
39
40
        return $ans[0];
41
    }
42
}
43