Reputation: 1
input:
m
rows, n
columns.process:
i
and collect the coins there.j
, with cost |i-j|
, and collect the coins.output:
is there a O(mn)
algorithm for this problem?
Upvotes: 0
Views: 227
Reputation: 318
We are supposed to have a matrix[n][m] (n - rows, m - columns).
Let's determine injm as a sum of a column starting from a injm coordinates in a matrix to the end of the matrix.
Let's introduce this statement as the first sum:
Σ1 = i1j1 + i1j2 + i1j3 + ... + i1jm
So basically we are moving down the matrix and summing all the columns there for the Σ1.
The next sums will be:
Σ2 = i1j1 + i1j2 + i1j3 + ... + i2jm
Σ3 = i1j1 + i1j2 + i1j3 + ... + i3jm
Σ4 = i1j1 + i1j2 + i1j3 + ... + i4jm
And so on until we have
Σn = i1j1 + i1j2 + i1j3 + ... + injm
Now, we have to move to the next column by increasing the index of the previous element by 1 and returning to the index of 1 of the last:
Σn+1 = i1j1 + i1j2 + i1j3 + ... + i2jm-1 + i1jm
After that, it's obvious to continue like in the first steps:
Σn+2 = i1j1 + i1j2 + i1j3 + ... + i2jm-1 + i2jm
Σn+3 = i1j1 + i1j2 + i1j3 + ... + i2jm-1 + i3jm
Σn+4 = i1j1 + i1j2 + i1j3 + ... + i2jm-1 + i4jm
Comparing all the sums Σ (until you'll be on a injm) you will have the largest sum!
To use this algorithm it's good to have int matrix[n][m]
to store all the coins inside,
int index[n][2]
to store the indexes of the elements in the sums (n number of indexes for 2 elements), and int maxSum
to store the largest sum.
Upvotes: 0