Count Negative Numbers in a Column | Java 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
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int countNegative ( int M [ ] [ ] , 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 ; } public static void main ( String [ ] args ) { int M [ ] [ ] = { { - 3 , - 2 , - 1 , 1 } , { - 2 , 2 , 3 , 4 } , { 4 , 5 , 7 , 8 } } ; System . out . println ( countNegative ( M , 3 , 4 ) ) ; } }