2 minute read

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.

Example 1:

Input: mat = [[0,1],[1,0]] Output: [0,1] Explanation: Both rows have the same number of 1’s. So we return the index of the smaller row, 0, and the maximum count of ones (1). So, the answer is [0,1]. Example 2:

Input: mat = [[0,0,0],[0,1,1]] Output: [1,2] Explanation: The row indexed 1 has the maximum count of ones (2). So we return its index, 1, and the count. So, the answer is [1,2]. Example 3:

Input: mat = [[0,0],[1,1],[0,0]] Output: [1,2] Explanation: The row indexed 1 has the maximum count of ones (2). So the answer is [1,2].

Constraints:

m == mat.length n == mat[i].length 1 <= m, n <= 100 mat[i][j] is either 0 or 1.

/**
 * @param {number[][]} mat
 * @return {number[]}
 */
var rowAndMaximumOnes = function (mat) {
  // Initialize variables to store the maximum count of ones and the index of the row with the maximum count
  let maxOnes = 0;
  let maxIndex = 0;

  // Iterate through each row of the matrix
  for (let i = 0; i < mat.length; i++) {
    // Initialize a variable to count the number of ones in the current row
    let countOne = 0;

    // Iterate through each element in the current row
    for (let j = 0; j < mat[i].length; j++) {
      // If the current element is 1, increment the countOne variable
      if (mat[i][j] == 1) {
        countOne++;
      }
    }

    // Check if the countOne variable (number of ones in the current row) is greater than the maximum count of ones found so far
    if (maxOnes < countOne) {
      // If so, update the maximum count of ones and the index of the row with the maximum count
      maxOnes = countOne;
      maxIndex = i;
    }
  }

  // Return an array containing the index of the row with the maximum count of ones and the number of ones in that row
  return [maxIndex, maxOnes];
};

The time complexity of this code is O(n _ m), where n is the number of rows in the matrix and m is the number of columns in the matrix. This is because we iterate through each element in the matrix once, resulting in a nested loop that runs n _ m times.

The space complexity of this code is O(1) because we only use a constant amount of extra space to store the maximum count of ones and the index of the row with the maximum count.

Leave a comment