text: Count Negative Numbers in a Column | CPP implementation of Efficient method to count of negative numbers in M [ n ] [ m ] ; Function to count negative number ; initialize result ; Start with top right corner ; Follow the path shown using arrows above ; j is the index of the last negative number in this row . So there must be ( j + 1 ) ; negative numbers in this row . ; move to the left and see if we can find a negative number there ; Driver program to test above functions
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int countNegative ( int M [ ] [ 4 ] , int n , int m ) { int count = 0 ; int i = 0 ; int j = m - 1 ; while ( j >= 0 && i < n ) { if ( M [ i ] [ j ] < 0 ) { count += j + 1 ; i += 1 ; } else j -= 1 ; } return count ; } int main ( ) { int M [ 3 ] [ 4 ] = { { -3 , -2 , -1 , 1 } , { -2 , 2 , 3 , 4 } , { 4 , 5 , 7 , 8 } } ; cout << countNegative ( M , 3 , 4 ) ; return 0 ; }