Flipping the Matrix HackerRank Problem Solution

In this Flipping the Matrix HackerRank Problem, Sean invented a game involving a  matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the  submatrix located in the upper-left quadrant of the matrix.

Given the initial configurations for  matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix’s upper-left quadrant is maximal.

Example

1 2
3 4

It is  and we want to maximize the top left quadrant, a  matrix. Reverse row :

1 2
4 3

And now reverse column :

4 2
1 3

The maximal sum is .

Function Description

Complete the flippingMatrix function in the editor below.

flippingMatrix has the following parameters:
 int matrix[2n][2n]: a 2-dimensional array of integers

Returns
 int: the maximum sum possible.

Input Format

The first line contains an integer , the number of queries.

The next  sets of lines are in the following format:

  • The first line of each query contains an integer, .
  • Each of the next  lines contains  space-separated integers  in row  of the matrix.

Constraints

  • , where .

Flipping the Matrix Hacker Rank Problem Solutions

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in JavaScript

function flippingMatrix(matrix) {
    const n = matrix.length / 2
    let sum = 0;
    function getMirrors(i,j) {
        return [
            matrix[i][j],
            matrix[i][n * 2 - 1 - j],
            matrix[n * 2 - 1 - i][j],
            matrix[n * 2 - 1 - i][n * 2 - 1 - j]
        ]
    }
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            sum += Math.max(...getMirrors(i,j))
        }
    }
    
    return sum
}

Problem Solution in C++Java

public static int flippingMatrix(List<List<Integer>> matrix) {
        int sum = 0;
        int size = matrix.size();
        for (int i = 0; i < size/2; i++) {
            for (int j = 0; j < size/2; j++) {
                sum += Math.max( matrix.get(i).get(j),
                    Math.max( matrix.get(i).get(size-1-j),
                    Math.max( matrix.get(size-1-i).get(j),
                        matrix.get(size-1-i).get(size-1-j))
                    )  
                );
            }            
        }
        return sum;
    }
}

Leave a Comment