Find number of subarrays with even sum | PHP program to count number of sub - arrays whose sum is even using brute force Time Complexity - O ( N ^ 2 ) Space Complexity - O ( 1 ) ; Find sum of all subarrays and increment result if sum is even ; Driver code
< ? php function countEvenSum ( $ arr , $ n ) { $ result = 0 ; for ( $ i = 0 ; $ i <= $ n - 1 ; $ i ++ ) { $ sum = 0 ; for ( $ j = $ i ; $ j <= $ n - 1 ; $ j ++ ) { $ sum = $ sum + $ arr [ $ j ] ; if ( $ sum % 2 == 0 ) $ result ++ ; } } return ( $ result ) ; } $ arr = array ( 1 , 2 , 2 , 3 , 4 , 1 ) ; $ n = sizeof ( $ arr ) ; echo " The ▁ Number ▁ of ▁ Subarrays ▁ " , " with ▁ even ▁ sum ▁ is ▁ " , countEvenSum ( $ arr , $ n ) ; ? >