Open In App

Find the minimum difference of 1s between two vertical halves of the given matrix

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary square matrix M[][] of size NXN, where N is an even number. The task is to find the minimum difference of frequency of 1s between the first and the second vertical half of M[][]. We can apply the below operations at most once:

  • Choose any one row out of N rows of M[][] and reverse it in.

Examples:

Input: N = 6, M [][] = {100000, 100000, 100000, 100000, 010010, 001100}

t1

Input Matrix

Output: 2

Explanation:

  • Initially in M[][]:
    • First half (First 3 columns): (Count of 1s) = 6
    • Second half (Last 3 columns): (Count of 1s) = 2
    • Initial difference: |6-2| = 4

    t2

    Count of 1s in both halves initially

  • After Using operation:
    • Let us reverse the 1st row. Now, If we see the difference of count in both halves, It is |5-3| = 2. Because count of 1s is 5 in first half and 3 in second. So, 2 is the minimum possible difference that can be achieved. Therefore, output is 2.

    t2

    Matrix after applying one operation

Input: N = 4, M[][] = {0011, 1100, 1110, 0001}

Output: 0

Explanation: Initial difference between count of 1s of both vertical halves is: |4-4| = 0. The minimum possible difference is already 0 initially. Hence, no need to use operation.

Approach: The problem can be solved using the following approach:

The problem can be solved by storing the difference of 1s between the first half and the second half for each row and storing it in an array, say diff[]. If we observe carefully, we get to know that if we swap a row whose difference between first and second half is +D, then after the swap the difference becomes -D. So, now the problem is reduced to minimize the absolute sum of all the elements in the array diff[] such that we can change the sign of a single number.

Steps to solve the problem:

  • Calculate the difference between the first half and the second half and store it in an array diff[].
  • Calculate the sum of the array diff[].
  • For each element, change the sign of the current element and calculate the new sum.
  • Update the answer if the new sum is smaller than the previous sum.
  • Print the final answer.

Implementation:

C++




// CPP program for the above approach
#include <iostream>
using namespace std;
 
// Function to print the minimum difference
void MinimumDifference(int N, int M[][6])
{
    // Array to store the difference of the number of 1s
    // between the first and the second half
    int diff[N];
 
    // Variable to store the sum of all differences
    int sum = 0;
 
    for (int i = 0; i < N; i++) {
        int D = 0;
        for (int j = 0; j < N; j++) {
            if (M[i][j] == 1) {
                // If 1 lies in the first half
                if (j < N / 2) {
                    D += 1;
                }
                // If 1 lies in the second half
                else {
                    D -= 1;
                }
            }
        }
        diff[i] = D;
        sum += D;
    }
 
    int ans = sum;
    // Reverse the sign of the difference of all rows to get
    // the answer
    for (int i = 0; i < N; i++) {
        ans = min(ans, sum - 2 * diff[i]);
    }
    cout << ans << endl;
}
 
// Driver Code
int main()
{
    // Input
    int N = 6;
    int M[][6]
        = { { 1, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0, 0 },
            { 1, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0, 0 },
            { 0, 1, 0, 0, 1, 0 }, { 0, 0, 1, 1, 0, 0 } };
 
    // Function call
    MinimumDifference(N, M);
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Java




// Java code to implement the approach
 
import java.util.*;
 
// Driver Class
class GFG {
 
    // Driver Function
    public static void main(String[] args)
        throws java.lang.Exception
    {
 
        // Input
        int N = 6;
        int M[][] = {
            { 1, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0, 0 },
            { 1, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0, 0 },
            { 0, 1, 0, 0, 1, 0 }, { 0, 0, 1, 1, 0, 0 }
        };
        // function call
        Minimum_difference(N, M);
    }
 
    // Method to print the minimum difference
    public static void Minimum_difference(int N, int[][] M)
    {
        // Array to store difference of number of 1s between
        // the first and the second half
        int diff[] = new int[N];
 
        // Variable to store the sum of all differences
        int sum = 0;
 
        for (int i = 0; i < N; i++) {
            int D = 0;
            for (int j = 0; j < N; j++) {
                if (M[i][j] == 1) {
                    // If 1 lies in the first half
                    if (j < N / 2) {
                        D += 1;
                    }
                    // If 1 lies in the second half
                    else {
                        D -= 1;
                    }
                }
            }
            diff[i] = D;
            sum += D;
        }
        int ans = sum;
        // Reverse the sign of difference of all rows to get
        // the answer
        for (int i = 0; i < N; i++) {
            ans = Math.min(ans, sum - 2 * diff[i]);
        }
        System.out.println(ans);
    }
}


Python3




# Function to print the minimum difference
def MinimumDifference(N, M):
    # Array to store the difference of the number of 1s
    # between the first and the second half
    diff = [0]*N
 
    # Variable to store the sum of all differences
    sum = 0
 
    for i in range(N):
        D = 0
        for j in range(N):
            if M[i][j] == 1:
                # If 1 lies in the first half
                if j < N / 2:
                    D += 1
                # If 1 lies in the second half
                else:
                    D -= 1
        diff[i] = D
        sum += D
 
    ans = sum
    # Reverse the sign of the difference of all rows to get
    # the answer
    for i in range(N):
        ans = min(ans, sum - 2 * diff[i])
    print(ans)
 
# Driver Code
 
N = 6
M = [[1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0],
     [1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0]]
 
# Function call
MinimumDifference(N, M)


C#




using System;
 
class Program
{
    // Function to print the minimum difference
    static void MinimumDifference(int N, int[,] M)
    {
        // Array to store the difference of the number of 1s
        // between the first and the second half
        int[] diff = new int[N];
 
        // Variable to store the sum of all differences
        int sum = 0;
 
        for (int i = 0; i < N; i++)
        {
            int D = 0;
            for (int j = 0; j < N; j++)
            {
                if (M[i, j] == 1)
                {
                    // If 1 lies in the first half
                    if (j < N / 2)
                    {
                        D += 1;
                    }
                    // If 1 lies in the second half
                    else
                    {
                        D -= 1;
                    }
                }
            }
            diff[i] = D;
            sum += D;
        }
 
        int ans = sum;
        // Reverse the sign of the difference of all rows to get
        // the answer
        for (int i = 0; i < N; i++)
        {
            ans = Math.Min(ans, sum - 2 * diff[i]);
        }
        Console.WriteLine(ans);
    }
 
    // Driver Code
    static void Main()
    {
        // Input
        int N = 6;
        int[,] M = {
            { 1, 0, 0, 0, 0, 0 },
            { 1, 0, 0, 0, 0, 0 },
            { 1, 0, 0, 0, 0, 0 },
            { 1, 0, 0, 0, 0, 0 },
            { 0, 1, 0, 0, 1, 0 },
            { 0, 0, 1, 1, 0, 0 }
        };
 
        // Function call
        MinimumDifference(N, M);
    }
}


Javascript




// JavaScript code to implement the approach
 
// Function to calculate the minimum difference
function minimumDifference(N, M) {
    // Array to store difference of number of 1s between
    // the first and the second half
    const diff = new Array(N).fill(0);
 
    // Variable to store the sum of all differences
    let sum = 0;
 
    for (let i = 0; i < N; i++) {
        let D = 0;
        for (let j = 0; j < N; j++) {
            if (M[i][j] === 1) {
                // If 1 lies in the first half
                if (j < N / 2) {
                    D += 1;
                }
                // If 1 lies in the second half
                else {
                    D -= 1;
                }
            }
        }
        diff[i] = D;
        sum += D;
    }
    let ans = sum;
 
    // Reverse the sign of difference of all rows to get
    // the answer
    for (let i = 0; i < N; i++) {
        ans = Math.min(ans, sum - 2 * diff[i]);
    }
    console.log(ans);
}
 
// Provided Input
const N = 6;
const M = [
    [1, 0, 0, 0, 0, 0],
    [1, 0, 0, 0, 0, 0],
    [1, 0, 0, 0, 0, 0],
    [1, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 1, 0],
    [0, 0, 1, 1, 0, 0]
];
 
// Function call
minimumDifference(N, M);


Output

2


Time Complexity: O(N * N), where N is the number of rows or columns in the input grid M[][].
Auxiliary Space: O(N)



    Like Article
    Suggest improvement
    Share your thoughts in the comments

    Similar Reads