简体   繁体   中英

Minimum swaps needed to maximize sum of nth row of a 2D array?

I am experimenting with different array sizes and elements. For simplicity I'm taking an array of size: 3x3. In a form of 2D list as follows:

input_matrix = [[80,81,84],[69,80,51],[13,37,65]]

So, what might be a best way to do it? If I use nested loops, that would be an overkill to such simple task with O(n^2) complexity which I want to avoid.

EDIT 1:

By Sum maximization I meant that I can swap elements within the array and for each arrangement in first row there would be a different sum. So how many swaps do I need to get that arrangement for which the sum of the rows is maximum of all the possible sums that can be achieved by putting elements from whole array into the first row

If you can swap only across columns:

By row maximization I assumed you meant you can swap vertically in an array to make a row maximum. In that case it can be done via numpy as follows:

(np.argmax(np.array(input_matrix), axis = 0)!=r).sum()

Trick here is to find the maximum element of each column and then if its not in the required row (ie r) then count it as a swap because thats where you need to swap and sum it.

If you can swap any element from the array:

In case where you can take values from whole array you need a more complex mechanism as follows:

def largest_indices(ary, n):
    """Returns the n largest indices from a numpy array."""
    flat = ary.flatten()
    indices = np.argpartition(flat, -n)[-n:]
    indices = indices[np.argsort(-flat[indices])]
    return np.unravel_index(indices, ary.shape)

(largest_indices(np.array(input_matrix), len(input_matrix[0]))[0]!=r).sum()

It goes on to find n maximum elements across the array, finds their indices and if they are not in the required row, it counts them as swaps and return total number of swaps. Function credit goes to this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM