Number of sub arrays with odd sum | PHP proggram to find count of sub - arrays with odd sum ; A temporary array of size 2. temp [ 0 ] is going to store count of even subarrays and temp [ 1 ] count of odd . temp [ 0 ] is initialized as 1 because there is a single odd element is also counted as a subarray ; Initialize count . sum is sum of elements under modulo 2 and ending with arr [ i ] . ; i ' th ▁ iteration ▁ computes ▁ sum ▁ ▁ of ▁ arr [ 0 . . i ] ▁ under ▁ modulo ▁ 2 ▁ ▁ and ▁ increments ▁ even / odd ▁ count ▁ ▁ according ▁ to ▁ sum ' s value ; 2 is added to handle negative numbers ; Increment even / odd count ; An odd can be formed by even - odd pair ; Driver code
< ? php function countOddSum ( $ ar , $ n ) { $ temp = array ( 1 , 0 ) ; $ result = 0 ; $ val = 0 ; for ( $ i = 0 ; $ i <= $ n - 1 ; $ i ++ ) { $ val = ( ( $ val + $ ar [ $ i ] ) % 2 + 2 ) % 2 ; $ temp [ $ val ] ++ ; } $ result = ( $ temp [ 0 ] * $ temp [ 1 ] ) ; return ( $ result ) ; } $ ar = array ( 5 , 4 , 4 , 5 , 1 , 3 ) ; $ n = sizeof ( $ ar ) ; echo " The ▁ Number ▁ of ▁ Subarrays ▁ with ▁ odd " . " ▁ sum ▁ is ▁ " . countOddSum ( $ ar , $ n ) ; ? >