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

• Difficulty Level : Medium
• Last Updated : 09 Jun, 2022

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

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 using namespace std; // Function to find the maximum scorevoid maxScoreSum(vector >& a,                 vector >& b){    // Stores the maximum sum of scores    int maxSum = 0;     vector 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 Codeint main(){    int N = 3, M = 3;    vector > a        = { { 1, 1, 0 }, { 1, 0, 1 }, { 0, 0, 1 } };    vector > b        = { { 1, 0, 0 }, { 0, 0, 1 }, { 1, 1, 0 } };     maxScoreSum(a, b);     return 0;}

## Python3

 # Python Program to implement# the above approachdef next_permutation(array):    i = len(array) - 1    while (i > 0 and array[i - 1] >= array[i]):        i -= 1     if (i <= 0):        return False     j = len(array) - 1     while (array[j] <= array[i - 1]):        j -= 1     temp = array[i - 1]    array[i - 1] = array[j]    array[j] = temp     j = len(array) - 1     while (i < j):        temp = array[i];        array[i] = array[j];        array[j] = temp;        i += 1        j -= 1     return array # Function to find the maximum scoredef maxScoreSum(a, b):       # Stores the maximum sum of scores    maxSum = 0     pos = []    for i in range(len(a)):        pos.append(i)     # For each permutation of pos vector    # calculate the score    while(True):        curSum = 0        for i in range(len(a)):             for j in range(len(a[pos[i]])):                 # If values at current indexes                # are same then increment the                # current score                curSum += (a[pos[i]][j] == b[i][j])                maxSum = max(maxSum, curSum)         if(next_permutation(pos) == False):            break     # Print the maximum score    print(maxSum) # Driver CodeN, M = 3, 3a = [[1, 1, 0], [1, 0, 1], [0, 0, 1]]b = [[1, 0, 0], [0, 0, 1], [1, 1, 0]] maxScoreSum(a, b) # This code is contributed by shinjanpatra

## C#

 // C# program to implement above approachusing System;using System.Collections.Generic; class GFG{   public static List> perms = new List>();   public static void generate_permuatation(int mask, int ind, int N, List current){    if(ind == N){      List temp = new List(current);      perms.Add(temp);      return;    }    for(int i = 0 ; i < N ; i++){      if(((mask >> i) & 1) == 0){        current.Add(i);        generate_permuatation(mask | (1 << i), ind + 1, N, current);        current.RemoveAt(current.Count-1);      }    }  }   // Function to find the maximum score  public static void maxScoreSum(List> a, List> b)  {    // Stores the maximum sum of scores    int maxSum = 0;     generate_permuatation(0, 0, a.Count, new List());     // For each permutation of {0, a.Count - 1} vector    // calculate the score    for(int ind = 0 ; ind < perms.Count ; ind++){      List pos = perms[ind];      int curSum = 0;      for (int i = 0; i < a.Count ; i++) {         for (int j = 0 ; j < a[pos[i]].Count ; j++) {           // If values at current indexes          // are same then increment the          // current score          curSum += (a[pos[i]][j] == b[i][j] ? 1 : 0);          maxSum = Math.Max(maxSum, curSum);        }      }    }     // Print the maximum score    Console.Write(maxSum);  }   // Driver Code  public static void Main(string[] args){     // int N = 3;    // int M = 3;    List> a = new List>{      new List{ 1, 1, 0 },      new List{ 1, 0, 1 },      new List{ 0, 0, 1 }    };    List> b = new List>{      new List{ 1, 0, 0 },      new List{ 0, 0, 1 },      new List{ 1, 1, 0 }    };     maxScoreSum(a, b);   }} // This code is contributed by subhamgoyal2014.

## Javascript



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:

## Javascript



Output:

8

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

My Personal Notes arrow_drop_up