You are given an m x n matrix grid that is sorted in non-increasing order both row-wise and column-wise. Return the count of negative numbers in the matrix.
Function Signature
def count_negatives(grid: list[list[int]]) -> int:
Rules
-
Non-increasing row-wise means
grid[i][j] >= grid[i][j + 1]
, and non-increasing column-wise means
grid[i][j] >= grid[i + 1][j]
, for every index pair where both cells exist.
-
A number is negative when it is less than 0. Zero is not negative.
Constraints
-
m == len(grid)
-
n == len(grid[i])
-
1 <= m, n <= 125
-
-125 <= grid[i][j] <= 125
Examples
Input: grid = [[5,4,3,-2],[4,3,2,-2],[2,1,-1,-3],[-1,-2,-3,-4]]
Output: 8
Rows 0 and 1 each end with one negative number, row 2 has two (-1 and -3), and row 3 is entirely negative with four, so the total is 1 + 1 + 2 + 4 = 8.
Input: grid = [[4,3],[2,1]]
Output: 0
Every value is positive, so there are no negative numbers.
Input: grid = [[3,2],[1,0],[0,-1]]
Output: 1
The matrix does not have to be square. The zeros do not count, so only the -1 in the bottom-right cell is negative.