LeetCode 2643. Row With Maximum Ones Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2643. Row With Maximum Ones

Description

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.

Solutions

Solution 1: Simulation

We initialize an array ans = [0, 0] to store the index of the row with the most 1s and the count of 1s.

Then, we iterate through each row of the matrix:

  • Compute the number of 1s in the current row, denoted as cnt (since the matrix contains only 0s and 1s, we can directly sum up the row).
  • If ans[1] < cnt, update ans = [i, cnt].

After finishing the iteration, we return ans.

The time complexity is O(m × n), where m and n are the number of rows and columns in the matrix, respectively. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustC#
class Solution: def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]: ans = [0, 0] for i, row in enumerate(mat): cnt = sum(row) if ans[1] < cnt: ans = [i, cnt] return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !