Count Negative Numbers in a Sorted Matrix

Easy

Description

Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.

Examples

Input:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output:8
Explanation:

Row 0 [4,3,2,-1]: 1 negative (-1). Row 1 [3,2,1,-1]: 1 negative (-1). Row 2 [1,1,-1,-2]: 2 negatives (-1,-2). Row 3 [-1,-1,-2,-3]: 4 negatives. Total: 1+1+2+4 = 8.

Input:grid = [[1]]
Output:0
Explanation:

The only element is 1, which is not negative, so the count is 0.

Input:grid = [[3,2],[1,0],[-1,-2]]
Output:3
Explanation:

Row 0 [3,2]: 0 negatives. Row 1 [1,0]: 0 negatives. Row 2 [-1,-2]: 2 negatives (-1 and -2). Total: 0+0+2 = 2 negative numbers.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 100

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!