#2643
Easy Algorithms Row with maximum ones
Array Matrix
74.3% acceptance
Feb 25, 2026
594
23
Given a m x n binary matrix mat, find the 0-indexed position of the row that contains
the maximum count of ones, and the number of ones in that row.
In case there are multiple rows that have the maximum count of ones, the row with
the smallest row number should be selected.
Return an array containing the index of the row, and the number of ones in it.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn row_and_maximum_ones(mat: Vec<Vec<i32>>) -> Vec<i32> {
let mut best_row = 0;
let mut best_count = 0;
for (i, row) in mat.iter().enumerate() {
let count = row.iter().filter(|&&x| x == 1).count();
if count > best_count {
best_count = count;
best_row = i;
}
}
vec![best_row as i32, best_count as i32]
}
}