Count Negative Numbers in a Column | 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 Code
< ? php function countNegative ( $ M , $ n , $ m ) { $ count = 0 ; $ i = 0 ; $ j = $ m - 1 ; while ( $ j >= 0 and $ i < $ n ) { if ( $ M [ $ i ] [ $ j ] < 0 ) { $ count += $ j + 1 ; $ i += 1 ; } else $ j -= 1 ; } return $ count ; } $ M = array ( array ( -3 , -2 , -1 , 1 ) , array ( -2 , 2 , 3 , 4 ) , array ( 4 , 5 , 7 , 8 ) ) ; echo countNegative ( $ M , 3 , 4 ) ; return 0 ; ? >