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 . "]";
}
}
}
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 :