Grokking Data Structures & Algorithms for Coding Interviews
Vote
0% completed
Solution: Row With Maximum Ones(easy)
Problem Statement
Given a binary matrix that has dimensions m * n, consisting of ones and zeros. Determine the row that contains the highest number of ones and return two values: the zero-based index of this row and the actual count of ones it possesses.
If there is a tie, i.e., multiple rows contain the same maximum number of ones, we must select the row with the lowest index.
Examples
Example 1:
- Input:
[[1, 0], [1, 1], [0, 1]] - Expected Output:
[1, 2] - Justification: The second row
[1, 1]contains the most ones, so the output is[1, 2].
.....
.....
.....
Like the course? Get enrolled and start learning!
L
luidymorais
· 3 years ago
Despite the solution explanation tells maxOnexIdx variable will initialize with -1, the code is showing is starting with zero. What is expected behaviour if there is no Ones in 2D-matrix?
Show 1 reply
Tal Ya'akov
· 18 days ago
class Solution { findMaxOnesRow(mat) { let maxOnesIdx = 0; let maxOnesCount = 0; const reduced = mat.map(row => row.reduce( (sum, x) => sum + x ), 0); for (let m = reduced.length - 1; m > -1; m--) { const curr = reduced[m]; if (curr >= maxOnesCount) { maxOnesCount = curr; maxOnesIdx = m; } } return [maxOnesIdx, maxOnesCount]; } }