Skip to content
Related Articles

Related Articles

Improve Article

Minimize sum of an array having Bitwise AND of all its pairs present in a given matrix

  • Last Updated : 07 May, 2021

Given a square symmetric matrix mat[][] of size N, the task is to find the minimum sum possible of an array arr[] of size N, such that for i != j, the value of Bitwise AND of arr[i] and arr[j] is mat[i][j].

Examples:

Input: mat[][] = {{-1, 0, 1, 1, 1}, {0, -1, 2, 0, 2}, {1, 2, -1, 1, 3}, {1, 0, 1, -1, -1}, {1, 2, 3, 1, -1}}
Output: 10
Explanation:
The array that satisfy the above criteria is {1, 2, 3, 1, 3}.
The sum of array elements is 1 + 2 + 3 + 1 + 3 = 10, which is minimum.

Input: mat[][] = {{-1, 2, 3}, {2, -1, 7}, {3, 7, -1}}
Output: 17

Approach: The given problem can be solved based on the following observations: 



  • The binary representation of the Bitwise AND of two numbers have only those bit set that is set in both the numbers.
  • So from the property of Bitwise AND it can be observed that a number in the resultant array must have all the bit set that is set in at least one of the matrix elements in the ith row.
  • Therefore, the number at ith position in the resultant array is Bitwise OR of all the elements of the matrix at the ith row.

Follow the steps below to solve the problem:

  • Initialize a variable say sum to 0 that stores the minimum possible sum of the array.
  • Iterate over the range [0, N – 1] and add the value of Bitwise OR of all the elements of the matrix at the ith row except mat[i][i] to the variable sum.
  • After completing the above steps, print the value of the sum as the resultant possible sum.

Below is the implementation of the above approach:

C++




// C++ program of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum sum
// of the array such that Bitwise
// AND of arr[i] ana arr[j] is mat[i][j]
int findMinSum(vector<vector<int> > mat,
               int N)
{
    // Stores the minimum possible sum
    int sum = 0;
 
    // Traverse the range [0, N - 1]
    for (int i = 0; i < N; i++) {
 
        // Stores the Bitwise OR of
        // all the element of a row
        int res = 0;
 
        // Traverse the range [0, N - 1]
        for (int j = 0; j < N; j++) {
 
            // If i not equal to j
            if (i != j) {
 
                // Update the value of
                // res
                res |= mat[i][j];
            }
        }
 
        // Increment the sum by res
        sum += res;
    }
 
    // Return minimum possible sum
    return sum;
}
 
// Driver Code
int main()
{
    vector<vector<int> > mat
        = { { -1, 2, 3 }, { 9, -1, 7 }, { 4, 5, -1 } };
    int N = mat.size();
    cout << findMinSum(mat, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to find the minimum sum
// of the array such that Bitwise
// AND of arr[i] ana arr[j] is mat[i][j]
static int findMinSum(int mat[][], int N)
{
     
    // Stores the minimum possible sum
    int sum = 0;
 
    // Traverse the range [0, N - 1]
    for(int i = 0; i < N; i++)
    {
         
        // Stores the Bitwise OR of
        // all the element of a row
        int res = 0;
 
        // Traverse the range [0, N - 1]
        for(int j = 0; j < N; j++)
        {
             
            // If i not equal to j
            if (i != j)
            {
                 
                // Update the value of
                // res
                res |= mat[i][j];
            }
        }
 
        // Increment the sum by res
        sum += res;
    }
 
    // Return minimum possible sum
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
    int mat[][] = { { -1, 2, 3 },
                    { 9, -1, 7 },
                    { 4, 5, -1 } };
    int N = mat.length;
 
    System.out.println(findMinSum(mat, N));
}
}
 
// This code is contributed by Kingash

Python3




# Python 3 program of the above approach
 
# Function to find the minimum sum
# of the array such that Bitwise
# AND of arr[i] ana arr[j] is mat[i][j]
def findMinSum(mat, N):
   
    # Stores the minimum possible sum
    sum1 = 0
 
    # Traverse the range [0, N - 1]
    for i in range(N):
       
        # Stores the Bitwise OR of
        # all the element of a row
        res = 0
 
        # Traverse the range [0, N - 1]
        for j in range(N):
           
            # If i not equal to j
            if (i != j):
               
                # Update the value of
                # res
                res |= mat[i][j]
 
        # Increment the sum by res
        sum1 += res
 
    # Return minimum possible sum
    return sum1
 
  # Driver code
if __name__ == '__main__':
    mat = [[-1, 2, 3], [9, -1, 7], [4, 5,-1]]
    N = 3
    print(findMinSum(mat, N))
 
    # This code is contributed by ipg2016107.

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the minimum sum
// of the array such that Bitwise
// AND of arr[i] ana arr[j] is mat[i][j]
static int findMinSum(int[,] mat, int N)
{
     
    // Stores the minimum possible sum
    int sum = 0;
 
    // Traverse the range [0, N - 1]
    for(int i = 0; i < N; i++)
    {
         
        // Stores the Bitwise OR of
        // all the element of a row
        int res = 0;
 
        // Traverse the range [0, N - 1]
        for(int j = 0; j < N; j++)
        {
             
            // If i not equal to j
            if (i != j)
            {
                 
                // Update the value of
                // res
                res |= mat[i, j];
            }
        }
 
        // Increment the sum by res
        sum += res;
    }
 
    // Return minimum possible sum
    return sum;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[,] mat = { { -1, 2, 3 },
                   { 9, -1, 7 },
                   { 4, 5, -1 } };
    int N = mat.GetLength(0);
 
    Console.WriteLine(findMinSum(mat, N));
}
}
 
// This code is contributed by ukasp

Javascript




<script>
 
// Javascript program for the above approach 
 
// Function to find the minimum sum
// of the array such that Bitwise
// AND of arr[i] ana arr[j] is mat[i][j]
function findMinSum(mat, N)
{
     
    // Stores the minimum possible sum
    var sum = 0;
 
    // Traverse the range [0, N - 1]
    for(var i = 0; i < N; i++)
    {
         
        // Stores the Bitwise OR of
        // all the element of a row
        var res = 0;
 
        // Traverse the range [0, N - 1]
        for(var j = 0; j < N; j++)
        {
             
            // If i not equal to j
            if (i != j)
            {
                 
                // Update the value of
                // res
                res |= mat[i][j];
            }
        }
 
        // Increment the sum by res
        sum += res;
    }
 
    // Return minimum possible sum
    return sum;
}
 
// Driver Code
var mat = [ [ -1, 2, 3 ],
            [ 9, -1, 7 ],
            [ 4, 5, -1 ] ];
var N = mat.length;
 
document.write(findMinSum(mat, N));
 
// This code is contributed by Ankita saini
 
</script>
Output: 
23

 

Time Complexity: O(N2)
Auxiliary Space: O(1)

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :