Total Complexity | 9 |
Total Lines | 34 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
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++) { |
||
|
|||
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) |
||
41 | } |
||
42 | } |
||
43 |
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: