ClarkeRubber

UNSW ProgComp: Problem 5 - 2007

Jun 11th, 2012
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.97 KB | None | 0 0
  1. <?php
  2.  
  3. $input = <<<END
  4. 31
  5. -3 4 23 6 -5 6 -124 -2 4 0 16 -3 0 -6 15 9 -3 -4 -1 6 0 -3 2 -2 2 -2 -2 2 2 2 -2
  6. END;
  7.  
  8. //scrap the first line and turn the second line into an array
  9. $input = explode("\n", $input);
  10. array_shift($input);
  11. $input = explode(" ", $input[0]);
  12. //this is just going to have to be a brute force, sorry guys
  13.  
  14. //one loop for length
  15. //another loop for position start
  16. $max_sum = array(null, null, null); //sum, start, length
  17.  
  18. for($x = 1; $x < count($input); $x++){
  19.     //this loop is for length
  20.     for($y = 0; $y < count($input)-$x; $y++){
  21.         //this loop is for start position
  22.         $sum = 0;
  23.         for($z = $y; $z < $y+$x; $z++){
  24.             //this loop is for accumulation
  25.             $sum += $input[$z];
  26.         }
  27.         if($sum > $max_sum[0]){
  28.             $max_sum[0] = $sum;
  29.             $max_sum[1] = $y;
  30.             $max_sum[2] = $x;
  31.         }
  32.     }
  33. }
  34.  
  35. for($x = $max_sum[1]; $x < $max_sum[1]+$max_sum[2]; $x++){
  36.     if($x == $max_sum[1]){
  37.         echo $input[$x];
  38.     }else{
  39.         echo ' + '.$input[$x];
  40.     }
  41. }
  42. echo ' = '.$max_sum[0];
Advertisement
Add Comment
Please, Sign In to add comment