Advertisement
naren_paste

Count_Negative

Jan 27th, 2024
532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.59 KB | Source Code | 0 0
  1. def count_negative_numbers(matrix):
  2.     count = 0
  3.     row = 0
  4.     col = len(matrix[0]) - 1  # Start from the top-right corner
  5.  
  6.     while row < len(matrix) and col >= 0:
  7.         if matrix[row][col] < 0:
  8.             count += col + 1  # Add count of negative numbers in this column
  9.             row += 1  # Move to the next row
  10.         else:
  11.             col -= 1  # Move to the previous column
  12.  
  13.     return count
  14.  
  15. # Test the function with the provided example
  16. grid = [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]]
  17. print(count_negative_numbers(grid))  # Output should be 8
  18.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement