Leetcode 2643: Row With Maximum Ones

grid47
grid47
Exploring patterns and algorithms
Feb 16, 2024 6 min read

Given a binary matrix of size m x n, your task is to find the row that contains the highest number of 1’s. If there are multiple rows with the same count of 1’s, return the row with the smallest index. The output should contain the index of the row and the count of 1’s in that row.
Problem
Approach
Steps
Complexity
Input: The input consists of a binary matrix 'mat' with m rows and n columns. Each element in the matrix is either 0 or 1.
Example: mat = [[0, 1, 1], [1, 0, 1], [1, 1, 1]]
Constraints:
• 1 <= m, n <= 100
• mat[i][j] is either 0 or 1
Output: Return an array containing two integers: the index of the row with the maximum count of 1's and the number of 1's in that row.
Example: Output: [2, 3]
Constraints:
• The output array should contain the row index and the count of 1's in the selected row.
Goal: The goal is to find the row with the maximum number of 1's and return its index along with the count of 1's in that row.
Steps:
• Step 1: Initialize a variable to track the maximum count of 1's and the corresponding row index.
• Step 2: Traverse each row of the matrix and count the number of 1's in the row.
• Step 3: If the count of 1's in the current row exceeds the previous maximum, update the row index and the maximum count.
• Step 4: After processing all rows, return the row index and the count of 1's in the row with the maximum count.
Goal: The solution must efficiently process matrices up to size 100 x 100, and handle cases where all elements are 0's or 1's.
Steps:
• Ensure the solution operates in O(m * n) time, where m is the number of rows and n is the number of columns.
Assumptions:
• The matrix contains only 0's and 1's.
Input: Input: mat = [[0, 1, 1], [1, 0, 1], [1, 1, 1]]
Explanation: The first row has 2 ones, the second row has 2 ones, and the third row has 3 ones. The row with the maximum count of 1's is the third row (index 2), so the output is [2, 3].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus