Created
December 25, 2022 05:30
-
-
Save thmain/babbfcbc8125195ba741121686d602a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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