Base point: I'm looking for help on how to use Dynamic programming to solve the following problem. My current solution is a little out of control.
Problem: find the maximum sum from an NxN matrix combining only one element from each subarray, must choose elements from each of the columns. For example: [[1,2], [3,4]] The max sum would be 5. So either matrix[0][0] + matrix[1][1] or matrix[0][1] + matrix[1][0].
Should be able to run for n = 0...30.
I wrote the following function with sub-optimal time complexity:
var perm = function (values, currentCombo = [], allPerm = []) {
if (values.length < 1) {
allPerm.push(currentCombo);
return allPerm;
}
for (var i = 0; i < values.length; i++) {
var copy = values.slice(0);
var value = copy.splice(i, 1);
perm(copy, currentCombo.concat(value), allPerm);
}
return allPerm;
};
var maxSumMatrix = function(matrix){
var n = matrix.length;
var options = [];
for(let i = 0; i < n; i++){
let row = new Array(n).fill(0);
row[i] = 1;
options.push(row);
}
var paths = perm(options);
var accumMax = null;
for(var i = 0; i < paths.length; i++){
var sum = null;
for(var j = 0; j < paths[i].length; j++){
for(var k = 0; k < paths[i][j].length; k++){
sum += paths[i][j][k] * matrix[j][k];
}
if(accumMax === null || accumMax < sum){
accumMax = sum;
}
}
}
return accumMax;
}
So "perm" finds all 0,1 permutations of solutions, then I multiply each possible solution to the input matrix and find the max answer.
Thank you!
EDIT
So for the following matrix: [[1,2,4], [2,-1,0], [2,20,6]]; The greatest sum would be 26. From: matrix[0][2] + matrix[1][0] + matrix[2][1]
[[1, 2], [3, 4], [5, 6]] = 12? - fubarn x n, can you show a more complicated example - e.g. 3x3 or 4x4 to show how the value should be computed. - fubar