Count Negative Numbers in a Sorted Matrix

easy array binary search matrix

Problem

Given an m x n matrix grid whose rows and columns are both sorted in non-increasing order, return the count of negative numbers in grid.

Inputgrid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output8
Eight cells hold negative values.

def count_negatives(grid):
    m, n = len(grid), len(grid[0])
    r, c, ans = m - 1, 0, 0
    while r >= 0 and c < n:
        if grid[r][c] < 0:
            ans += n - c
            r -= 1
        else:
            c += 1
    return ans
function countNegatives(grid) {
  const m = grid.length, n = grid[0].length;
  let r = m - 1, c = 0, ans = 0;
  while (r >= 0 && c < n) {
    if (grid[r][c] < 0) { ans += n - c; r--; } else c++;
  }
  return ans;
}
class Solution {
    public int countNegatives(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int r = m - 1, c = 0, ans = 0;
        while (r >= 0 && c < n) {
            if (grid[r][c] < 0) { ans += n - c; r--; } else c++;
        }
        return ans;
    }
}
int countNegatives(vector>& grid) {
    int m = grid.size(), n = grid[0].size();
    int r = m - 1, c = 0, ans = 0;
    while (r >= 0 && c < n) {
        if (grid[r][c] < 0) { ans += n - c; r--; } else c++;
    }
    return ans;
}
Time: O(m + n) Space: O(1)