Search code examples
phparrayssumcombinationscontiguous

Find any number of distinct consecutive subarrays that have a given sum


I have a array called $A which contains only non zero positive numbers.

Now I need to find any number of distinct consecutive subarrays that have a given sum.

I will explain with example

$A = array(1, 2, 3, 4, 5);

and the sum I am looking for is 5.

Then there are (2, 3) and (5).

I tried searching and got a python code. I've translated it to PHP below but it refuses to work

$s = 0;
for ($i = 0; $i < count($A); $i++) {
     for ($j = $i; $j < count($A); $j++) {
         $s = $s + $A[$j];
         if ($s == $sum) {
             echo "[" . $i . " " . $j . "]";
         }
     }
}

Solution

  • This will work :

    $A = array(1, 2, 3, 4, 5);
    $size = count($A);
    $sum = 5;
    $solution = array();
    for($i = 0; $i < $size; $i++) {
        $tempsum = 0;
        for($j=$i; $j < $size && $tempsum < $sum; $j++) {
            $tempsum += $A[$j];
            if($tempsum === $sum) {
                $solution[] = array_slice($A, $i, $j - $i + 1);
            }
        }
    }
    
    var_dump($solution);
    

    As for your code, there's several mistake in it :

    1. You must reinitialize $s each time in the loop.
    2. The array $B probably doesn't exist (second loop stop condition).
    3. It won't show a proper result when the length of the subarray is greater than 2.
    4. There's no need the second loop go to the end, as soon as the temporary sum is greater than the searched one, we can stop.