Given a 2D-array and a number K.
PROBLEM: we have a matrix cost[][] and each cell of the matrix represents a cost to traverse through that cell. we start at the top left (0,0) and we have to reach the last cell (bottom right). I have to write a function that returns the cost of maximum cost path to reach (m,n) without exceeding the number K.
The total cost of a path to reach (m, n) is the sum of all the costs on that path (including both source and destination) and the sum should be less or equal than K. We can only move down, right or diagonally down-right.
If we can't find a path having a maximum sum less or equal than K we return -1 and the value of the matrix cannot be negative
Solution: I tried a lot of codes but none of them returned the results I expected.
My first solution was to transform the 2D array in a simple array and to apply the knapsack algorithm but it didn't work because logically the path were not followed. (the logic of the exercise disappeared with this idea)
I tried also a recursive formula but it didn't work. I got an error "max recursion depth". When I solved this recursion problem my algorithm didn't take into account the constraint of the number not to be exceeded.
I don't need the code, I just want some explanations to be able to solve the problem (especially the mathematical formula). thanks
Example:
if we had this 3*3 matrix:
cost[][] = {{2,3,1}, {6,1,9},{8,2,3}}
and k = 7
the answer should be 6 :(0,0)->(1,1)->(3,3)