Skip to content

Instantly share code, notes, and snippets.

@thmain
Created December 25, 2022 05:30
Show Gist options
  • Save thmain/babbfcbc8125195ba741121686d602a0 to your computer and use it in GitHub Desktop.
Save thmain/babbfcbc8125195ba741121686d602a0 to your computer and use it in GitHub Desktop.
const countNegative = ( M, n, m ) => {
var count = 0;
// start from top right
var i = 0;
var j = m - 1;
while ( j >= 0 && i < n ) {
if ( M[i][j] < 0 ) {
// last negative number is at index j. Hence, there j + 1 negative numebrs at index i
count += (j + 1);
// Move to the next row
i += 1;
} else {
// Move to the next column
j -= 1;
}
}
return count;
};
var M = [
[-3, -2, -1, 1],
[-2, -12, 3, 4],
[4, 5, 7, 8]
];
console.log(countNegative(M, 3, 4)); // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment