text: 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
code: def countNegative ( M , n , m ) : NEW_LINE INDENT count = 0 NEW_LINE i = 0 NEW_LINE j = m - 1 NEW_LINE while j >= 0 and i < n : NEW_LINE INDENT if M [ i ] [ j ] < 0 : NEW_LINE INDENT count += ( j + 1 ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT M = [ [ - 3 , - 2 , - 1 , 1 ] , [ - 2 , 2 , 3 , 4 ] , [ 4 , 5 , 7 , 8 ] ] NEW_LINE print ( countNegative ( M , 3 , 4 ) ) NEW_LINE