How to print all subarrays with zero sum in PHP

1 Answer

0 votes
function print_subarrays_with_zero_sum($arr) {
    for ($i = 0; $i < sizeof($arr); $i++) {
        $sum = 0;
        for ($j = $i; $j < sizeof($arr); $j++) {
            $sum += $arr[$j];
            if ($sum == 0) {
                echo "from: arr[" . $i . "] to: arr[" . $j . "]<br />";
            }
        }
    }
}

$arr = array(1, 2, -3, 3, 4, 1, -8, -5, 5, 6);

print_subarrays_with_zero_sum($arr);


/*
run:

from: arr[0] to: arr[2]
from: arr[0] to: arr[6]
from: arr[0] to: arr[8]
from: arr[2] to: arr[3]
from: arr[3] to: arr[6]
from: arr[3] to: arr[8]
from: arr[7] to: arr[8]

*/

 



answered Feb 15, 2019 by avibootz

Related questions

1 answer 178 views
1 answer 139 views
1 answer 164 views
164 views asked Feb 14, 2019 by avibootz
1 answer 150 views
1 answer 148 views
1 answer 144 views
...