2643. Row With Maximum Ones

ArrayMatrix

Explanation:

To solve this problem, we need to iterate through each row of the matrix and count the number of ones in each row. We will keep track of the row with the maximum count of ones and return its index along with the count.

  1. Initialize variables maxOnesRow and maxOnesCount to store the index of the row with maximum ones and the count.
  2. Iterate through each row of the matrix.
  3. For each row, count the number of ones and compare it with the current maximum count.
  4. If the current row has more ones than the previous maximum, update maxOnesRow and maxOnesCount.
  5. Return the index of the row with maximum ones and the count.

Time Complexity: O(m * n) where m is the number of rows and n is the number of columns in the matrix.

Space Complexity: O(1)

class Solution {
    public int[] rowWithMaxOnes(int[][] mat) {
        int maxOnesRow = -1;
        int maxOnesCount = 0;
        
        for (int i = 0; i < mat.length; i++) {
            int onesCount = 0;
            for (int j = 0; j < mat[i].length; j++) {
                if (mat[i][j] == 1) {
                    onesCount++;
                }
            }
            if (onesCount > maxOnesCount) {
                maxOnesRow = i;
                maxOnesCount = onesCount;
            }
        }
        
        return new int[]{maxOnesRow, maxOnesCount};
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.