I'm having a hard time thinking of a way to make a solution for a dynamic programming problem. Basically, I have to get from the top left to bottom right element in a NxN array, being able to move only down or right, but I should move to the bigger element and sum it in a variable (get highest score by moving only right and down). F.e., if I have this matrix:
0 1 1
0 4 2
1 1 1
It should move 0-> 1 -> 4 -> 2 -> 1 and print out 8. I've read about dynamic optimizing for a long time now and still can't get to solve this. Would appreciate if anybody could help me. Thanks in advance!
Edit: Thanks @sestus ! I've managed to solve the problem, however the solution is slow and I have to optimize it to perform faster. Here's my solution:
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 100;
int arr[MAX][MAX];
int move(int row,int col, int n)
{
if(row >= n || col >= n)
{
return 0;
}
return max(arr[row][col] + move(row + 1, col, n),
arr[row][col] + move(row, col + 1, n));
}
int main()
{
int examples, result;
cin>>examples;
int n;
int results[examples];
for(int k =1; k <= examples; k++)
{
cin >> n;
int s = 0;
int i = 0, j = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
cin>> arr[i][j];
}
}
i = 0, j = 0;
s+=move(i,j, n);
results[k] = s;
}
for(int k = 1; k <= examples; k++)
{
cout<<results[k]<<endl;
}
return 0;
}
(The programs actually has to take all the examples and output the answers for all of them at the end). Mind helping me with the optimizing?