Row With Maximum Ones

easy array matrix

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.

Inputmat = [[0,1],[1,0]]
Output[0,1]
Both rows have one 1; the smaller index 0 wins.

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};
}
Time: O(m · n) Space: O(1)