Number of sub arrays with negative product | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int negProdSubArr ( int arr [ ] , int n ) { int positive = 1 , negative = 0 ; for ( int 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 ) ; } int main ( ) { int arr [ ] = { 5 , -4 , -3 , 2 , -5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << negProdSubArr ( arr , n ) ; return ( 0 ) ; }