Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Maximize count of indices with same element by pairing rows from given Matrices

  • Difficulty Level : Medium
  • Last Updated : 06 Oct, 2021

Given two 2D binary arrays, a[][] and b[][] both of size M*N, the task is to pair each row in the array a[][] with any row in the array b[][] such that the total score can be maximized and the score for each pair is calculated as the total indexes at which values of both rows are identical.

Note: Each row of the array b[][] can only be paired with a single row of vector a[][].

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Examples:



Input: a[][] = {{1, 1, 0}, {1, 0, 1}, {0, 0, 1}}, b[][] = {{1, 0, 0}, {0, 0, 1}, {1, 1, 0}}
Output: 8
Explanation:
Consider the pairing of rows in the following order, to maximize the total score obtained:

  • Row 0 of a[][] paired with row 2 of b[][] has the score of 3.
  • Row 1 of a[][] paired with row 0 of b[][] with score of 2.
  • Row 2 of a[][] paired with row 1 of b[][] with score of 3.

Therefore, the sum of scores obtained is 3 + 2 + 3 = 8.

Input: a[][] = {{0, 0}, {0, 0}, {0, 0}}, b[][] = {{1, 1}, {1, 1}, {1, 1}}
Output: 0

Naive Approach: The simplest approach to solve the given problem is to generate all possible permutations of the rows of the arrays a[][]  and for each permutation of the array a[][], find the sum of scores of each corresponding pair, and if it’s greater than the current answer, update the answer to the value of the current sum of scores. After checking for all the pairs, print the maximum score obtained.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum score
void maxScoreSum(vector<vector<int> >& a,
                 vector<vector<int> >& b)
{
    // Stores the maximum sum of scores
    int maxSum = 0;
 
    vector<int> pos;
    for (int i = 0; i < a.size(); i++) {
        pos.push_back(i);
    }
 
    // For each permutation of pos vector
    // calculate the score
    do {
        int curSum = 0;
        for (int i = 0; i < a.size(); i++) {
 
            for (int j = 0;
                 j < a[pos[i]].size(); j++) {
 
                // If values at current indexes
                // are same then increment the
                // current score
                curSum += (a[pos[i]][j] == b[i][j]);
                maxSum = max(maxSum, curSum);
            }
        }
    } while (next_permutation(pos.begin(), pos.end()));
 
    // Print the maximum score
    cout << maxSum;
}
 
// Driver Code
int main()
{
    int N = 3, M = 3;
    vector<vector<int> > a
        = { { 1, 1, 0 }, { 1, 0, 1 }, { 0, 0, 1 } };
    vector<vector<int> > b
        = { { 1, 0, 0 }, { 0, 0, 1 }, { 1, 1, 0 } };
 
    maxScoreSum(a, b);
 
    return 0;
}

Javascript




<script>
        // JavaScript Program to implement
        // the above approach
        function next_permutation(array) {
            var i = array.length - 1;
            while (i > 0 && array[i - 1] >= array[i]) {
                i--;
            }
 
            if (i <= 0) {
                return false;
            }
 
            var j = array.length - 1;
 
            while (array[j] <= array[i - 1]) {
                j--;
            }
 
            var temp = array[i - 1];
            array[i - 1] = array[j];
            array[j] = temp;
 
            j = array.length - 1;
 
            while (i < j) {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
                i++;
                j--;
            }
 
            return array;
        }
        // Function to find the maximum score
        function maxScoreSum(a, b) {
            // Stores the maximum sum of scores
            let maxSum = 0;
 
            let pos = [];
            for (let i = 0; i < a.length; i++) {
                pos.push(i);
            }
 
            // For each permutation of pos vector
            // calculate the score
            do {
                let curSum = 0;
                for (let i = 0; i < a.length; i++) {
 
                    for (let j = 0;
                        j < a[pos[i]].length; j++) {
 
                        // If values at current indexes
                        // are same then increment the
                        // current score
                        curSum += (a[pos[i]][j] == b[i][j]);
                        maxSum = Math.max(maxSum, curSum);
                    }
                }
            } while (next_permutation(pos));
 
            // Print the maximum score
            document.write(maxSum);
        }
 
        // Driver Code
 
        let N = 3, M = 3;
        let a
            = [[1, 1, 0], [1, 0, 1], [0, 0, 1]];
        let b
            = [[1, 0, 0], [0, 0, 1], [1, 1, 0]];
 
        maxScoreSum(a, b);
 
     // This code is contributed by Potta Lokesh
 
    </script>

 
 

Output: 
8

 

 



Time Complexity: O(N*M*M!), where M! are the number of permutations and N*M for calculating the score of each pair.
Auxiliary Space: O(M)

 

Efficient Approach: The above approach can also be optimized using the concept of Bitmasking, The idea is for each row in vector a[][], try all rows in vector b[][] that haven’t been chosen before. Use a bitmask to represent already chosen rows of vector b[][]. To avoid re-computing the same subproblem, memoize the result for each bitmask. Follow the steps below to solve the problem:

 

  • Initialize the variables row as 0, mask as (2M – 1).
  • Initialize the vector dp[] of size mask + 1 with values -1.
  • If row is greater than equal to a.size() then return 0 and if dp[mask] is not equal to -1 then return dp[mask].
  • Initialize the variable ans as 0 to store the answer.
  • Iterate over the range [0, a.size()) using the variable i and perform the following tasks:
    • If the bitwise AND of mask and 2i is true then initialize the variable newMask as mask^(1<<i) and curSum as 0.
    • Iterate over the range [0, a[i].size()) using the variable j and if a[row][j] equals b[i][j] then increase the value of curSum by 1.
    • Set the value of ans as the maximum of ans or curSum + maxScoreSum(a, b, row+1, newmask, dp) recursively.
  • After performing the above steps, set the value of dp[mask] as ans and return the value of ans as the answer.

 

Below is the implementation of the above approach:

 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum defined
// score
int maxScoreSum(vector<vector<int> >& a,
                vector<vector<int> >& b,
                int row, int mask,
                vector<int>& dp)
{
    // If all students are assigned
    if (row >= a.size()) {
        return 0;
    }
    if (dp[mask] != -1) {
        return dp[mask];
    }
 
    int ans = 0;
 
    for (int i = 0; i < a.size(); i++) {
 
        // Check if row is not paired yet
        if (mask & (1 << i)) {
            int newMask = mask ^ (1 << i);
            int curSum = 0;
 
            // Check for all indexes
            for (int j = 0; j < a[i].size(); j++) {
 
                // If values at current indexes
                // are same increase curSum
                if (a[row][j] == b[i][j]) {
                    curSum++;
                }
            }
 
            // Further recursive call
            ans = max(
                ans, curSum
                         + maxScoreSum(
                               a, b, row + 1,
                               newMask, dp));
        }
    }
 
    // Store the ans for current
    // mask and return
    return dp[mask] = ans;
}
 
// Utility function to find the maximum
// defined score
int maxScoreSumUtil(vector<vector<int> >& a,
                    vector<vector<int> >& b,
                    int N, int M)
{
    int row = 0;
 
    // Create a mask with all set bits
    // 1 -> row is not paired yet
    // 0 -> row is already paired
    int mask = pow(2, M) - 1;
 
    // Initialise dp array with -1
    vector<int> dp(mask + 1, -1);
 
    return maxScoreSum(a, b, row, mask, dp);
}
 
// Driver Code
int main()
{
    int N = 3, M = 3;
    vector<vector<int> > a
        = { { 1, 1, 0 }, { 1, 0, 1 }, { 0, 0, 1 } };
    vector<vector<int> > b
        = { { 1, 0, 0 }, { 0, 0, 1 }, { 1, 1, 0 } };
 
    cout << maxScoreSumUtil(a, b, N, M);
 
    return 0;
}

Python3




# Python 3 program for the above approach
 
# Function to find the maximum defined
# score
def maxScoreSum(a, b, row, mask, dp):
 
    # If all students are assigned
    if (row >= len(a)):
        return 0
 
    if (dp[mask] != -1):
        return dp[mask]
 
    ans = 0
 
    for i in range(len(a)):
 
        # Check if row is not paired yet
        if (mask & (1 << i)):
            newMask = mask ^ (1 << i)
            curSum = 0
 
            # Check for all indexes
            for j in range(len(a[i])):
 
                # If values at current indexes
                # are same increase curSum
                if (a[row][j] == b[i][j]):
                    curSum += 1
 
            # Further recursive call
            ans = max(
                ans, curSum
                + maxScoreSum(
                    a, b, row + 1,
                    newMask, dp))
 
    # Store the ans for current
    # mask and return
    dp[mask] = ans
    return dp[mask]
 
# Utility function to find the maximum
# defined score
def maxScoreSumUtil(a,
                    b,
                    N, M):
 
    row = 0
 
    # Create a mask with all set bits
    # 1 -> row is not paired yet
    # 0 -> row is already paired
    mask = pow(2, M) - 1
 
    # Initialise dp array with -1
    dp = [-1]*(mask + 1)
 
    return maxScoreSum(a, b, row, mask, dp)
 
# Driver Code
if __name__ == "__main__":
 
    N = 3
    M = 3
    a = [[1, 1, 0], [1, 0, 1], [0, 0, 1]]
    b = [[1, 0, 0], [0, 0, 1], [1, 1, 0]]
 
    print(maxScoreSumUtil(a, b, N, M))
 
    # This code is contributed by ukasp.

 
 

Output: 
8

 

 

Time Complexity: O(2M*M*N)
Auxiliary Space: O(2M)

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!