Minimum operations of given type to make all elements of a matrix equal

Given a matrix of integers A of size N x M and an integer B.

In a single operation, B can be added to or subtracted from any element of the matrix.

Find and return the minimum number of operations required to make all the elements of the matrix equal and
if it impossible return -1 instead.

Note: Rows are numbered from top to bottom and columns are numbered from left to right.



Input Format

The first argument given is the integer matrix A.
The second argument given is the integer B.

Output Format

Return the minimum number of operations required to make all the elements of the matrix equal and if it impossible return -1 instead.

Constraints

1 <= N, M <= 1000
-1000 <= A[i] <= 1000
1 <= B <= 1000

For Example

Input 1:
    A = [   [0, 2, 8]
            [8, 2, 0]
            [0, 2, 8]   ]
    B = 2
Output 1:
    12

Input 2:
    A = [   [5, 17, 100, 11]
            [0, 0,  2,   8]    ]
    B = 3
Output 2:
    -1
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Minimum operations of given type to make all elements of a matrix equal on Interview Code Editor
Sign Up
to access hints and editorial solutions for Minimum operations of given type to make all elements of a matrix equal

Discussion


Loading...
Click here to start solving coding interview questions