Project Euler #67: Maximum path sum II

  • + 0 comments

    In PHP

    Since I'll be using a bottom-up approach, I've assembled the triangle in reverse before calling the solution function

    <?php
    
    function solution($triangle) {
        $len = count($triangle);
        foreach ($triangle as $i => &$curr) {
            if ($i == $len - 1) {
                return $curr[0];
            }
            
            $next = &$triangle[$i + 1];
            foreach ($next as $j => $val) {
                $next[$j] += max($curr[$j], $curr[$j + 1]);
            }
        }
    }
    
    $_fp = fopen("php://stdin", "r");
    $q = intval(trim(fgets($_fp)));
    
    while ($q--) {
        $j = intval(trim(fgets($_fp)));
        $triangle = array_fill(0, $j, null);
        while ($j--) {
            $triangle[$j] = array_map('intval', explode(' ', trim(fgets($_fp))));
        }
        echo solution($triangle), PHP_EOL;
    }
    
    fclose($_fp);