Number of sub arrays with negative product | Function to return the count of subarrays with negative product ; Replace current element with 1 if it is positive else replace it with - 1 instead ; Take product with previous element to form the prefix product ; Count positive and negative elements in the prefix product array ; Return the required count of subarrays ; Driver code
function negProdSubArr ( arr , n ) { let positive = 1 , negative = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) arr [ i ] = 1 ; else arr [ i ] = - 1 ; if ( i > 0 ) arr [ i ] *= arr [ i - 1 ] ; if ( arr [ i ] == 1 ) positive ++ ; else negative ++ ; } return ( positive * negative ) ; } let arr = [ 5 , - 4 , - 3 , 2 , - 5 ] ; let n = arr . length ; document . write ( negProdSubArr ( arr , n ) ) ;