Having a Matrix M of size m, n over integers, what would be a good algorithm to transform it such that the sum of all elements is maximal?

The only operations allowed are multiplying by -1 column-wise or row-wise. There can be executed as many such operations as required.

Rough, overall idea: What I have thought about is to move each minus sign from one such negative number to the positive number whose value is smallest, such that the minus would have the least influence on the sum.

Let's take for instance:

import numpy as np

M = np.matrix([
        [2,2,2,2],
        [2,2,-2,2],
        [2,2,2,2],
        [2,2,2,1],
    ])

def invert_at(M, n, m):
    M[n,:] *= -1
    M[:,m] *= -1

I've tried this by building one of the shortest paths from the negative element to the smallest number and invert_at each cell on the way there.

First by including the start and end cells:

invert_at(M, 1, 2)  # start
invert_at(M, 2, 2)
invert_at(M, 3, 2)
invert_at(M, 3, 3)  # end

I end up with:

[[ 2  2 -2 -2]
 [-2 -2 -2  2]
 [-2 -2  2  2]
 [ 2  2 -2 -1]]

which kind of looks interesting. It pushes the minus to the -1 in the bottom right corner, but also to some other areas. Now if I would invert again at the start and the end position (that is, -1 * -1 = 1), so leaving out the start and end cells in the first place, I end up with:

[[ 2  2  2  2]
 [ 2  2 -2  2]
 [-2 -2 -2 -2]
 [-2 -2 -2 -1]]

which looks better, considering I want to get at

[[ 2  2  2  2]
 [ 2  2  2  2]
 [ 2  2  2  2]
 [ 2  2  2 -1]]

by "pushing" the minus towards the right "half" of the matrix.

Talking about "halves", I've also played (a lot) with the idea of using partitions of the matrix, but I couldn't observe any usable patterns.

Edit
Report