Row With Maximum Ones
Problem
Given a binary matrix mat, find the row with the maximum number of 1s and return [rowIndex, count]. If multiple rows tie, return the one with the smallest index.
mat = [[0,1],[1,0]][0,1]def row_and_maximum_ones(mat):
best_row, best_count = 0, -1
for i, row in enumerate(mat):
ones = sum(row)
if ones > best_count:
best_count = ones
best_row = i
return [best_row, best_count]
function rowAndMaximumOnes(mat) {
let bestRow = 0, bestCount = -1;
for (let i = 0; i < mat.length; i++) {
const ones = mat[i].reduce((a, b) => a + b, 0);
if (ones > bestCount) { bestCount = ones; bestRow = i; }
}
return [bestRow, bestCount];
}
class Solution {
public int[] rowAndMaximumOnes(int[][] mat) {
int bestRow = 0, bestCount = -1;
for (int i = 0; i < mat.length; i++) {
int ones = 0;
for (int v : mat[i]) ones += v;
if (ones > bestCount) { bestCount = ones; bestRow = i; }
}
return new int[]{bestRow, bestCount};
}
}
vector<int> rowAndMaximumOnes(vector<vector<int>>& mat) {
int bestRow = 0, bestCount = -1;
for (int i = 0; i < (int)mat.size(); i++) {
int ones = 0;
for (int v : mat[i]) ones += v;
if (ones > bestCount) { bestCount = ones; bestRow = i; }
}
return {bestRow, bestCount};
}
Explanation
Because the matrix is binary, the number of 1s in a row is simply the sum of that row. So the task reduces to finding the row with the largest sum and reporting its index alongside the count.
We track two values, bestRow and bestCount, starting bestCount at -1 so any real row replaces it. We walk the rows top to bottom, summing each one.
A row replaces the current best only when its count is strictly greater. Using strict > is the key to the tie rule: a later row that merely ties does not overwrite the earlier one, so the smallest index is preserved automatically.
Every cell is visited exactly once while summing rows, giving O(m·n) time and O(1) extra space beyond the answer.
Example: [[0,1],[1,0]]. Row 0 has one 1 → best becomes (0, 1). Row 1 also has one 1, but 1 > 1 is false, so the best stays at row 0. Answer: [0, 1].