Menu Close

Leetcode 2643: Row With Maximum Ones Solution

Here, we are going to see Row With Maximum Ones Solution of leetcode 2643 problem with code and example in C++.

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].

Row With Maximum Ones Solution of leetcode 2643 in C++:

Here, we will be solving problem in multiple ways with code.

C++ code 1:

class Solution {

public:

    vector<int> rowAndMaximumOnes(vector<vector<int>>& mat) {

        int max_count = 0;

        vector<int> res(2);
        
        for(int i = 0; i < mat.size(); i++) {

            int one_count = 0;

            
            for(int j = 0; j < mat[0].size(); j++) {

                if(mat[i][j] == 1) {

                    one_count++;

                }

            }

            if(one_count && max_count < one_count) {

                max_count = one_count;

                res.clear();

                res.push_back(i);

                res.push_back(max_count);

            }

        }

        return res;

    }

};

C++ code 2:

class Solution {

public:
    vector<int> rowAndMaximumOnes(vector<vector<int>>& mat) {
        
        vector<vector<int>> v;
        
        for(int i=0;i<mat.size();i++)
        {
            int cnt=0;
            
            for(int j=0;j<mat[i].size();j++)
            {
                cnt+=mat[i][j];
            }
            
            v.push_back({cnt,-i});
        }
        
        sort(v.rbegin(),v.rend());
        
        return {-v[0][1],v[0][0]};
    }
};

Output:

Input: mat = [[0,1],[1,0]]
Output: [0,1]

Time complexity: O(n**2)

Space complexity: O(1)

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

https://www.techieindoor.com/category/interview-questions/

https://leetcode.com/

Posted in C++, Easy, Leetcode

Leave a Reply

Your email address will not be published. Required fields are marked *