We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. All Contests
  2. ProjectEuler+
  3. Project Euler #67: Maximum path sum II
  4. Discussions

Project Euler #67: Maximum path sum II

Problem
Submissions
Leaderboard
Discussions

    You are viewing a single comment's thread. Return to all comments →

  • willianmonts
    8 months ago+ 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);
    
    0|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy